I've migrated my blog

Thanks for visiting my blog. I am no longer maintaining this and I've migrated the blog to my personal domain . If you would like to follow my blog kindly use my new RSS feed

Wednesday, February 23, 2011

Ajax Update master page from content Page

Hi,
In this blog post we are going to see how can we update the master page from content page using ajax updatepanel in ASP.NET.
The sample website we are going to build will have a content page which allows to change the header of the website(which is present in master page).


The tasks involved in creating this website are as follows:
1. Create an updatepanel in masterpage which holds the website header.
2. Create a method in MasterPage codebehind which changes the website header.
3. Create the content page with master page reference and an update panel which holds controls to triggers the header change.
4. Call the MasterPage method from content page.
1. Create an updatepanel in masterpage which holds the website header.
<div class="title">
<h1>
<asp:UpdatePanel ID="UpdatePanelWebsiteHeader" runat="server"
ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblWebsiteHeader" runat="server" Text="Label">
My ASP.NET Application
</asp:Label>
</ContentTemplate>
</asp:UpdatePanel>                    
</h1>
</div>

Make Sure the two properties of UpdatePanel "ChildrenAsTriggers" is set to false and "UpdateMode" is set to conditional, to prevent the unneccessary updation of updatepanel from its child controls.
2. Create a method in MasterPage codebehind which changes the website header.

public void ChangeWebsiteHeader(string newHeader)
{
lblWebsiteHeader.Text = newHeader;
/* Calling the Update method of UpdatePanel will trigger 
the updation of the Updatepanel */
UpdatePanelWebsiteHeader.Update();
}

3. Create the content page with master page reference and an update panel which holds controls to triggers the header change.
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ MasterType VirtualPath="~/Site.master" %>
<asp:UpdatePanel ID="UpdatePanelChangeHeader" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<p>
Enter the Website Header: <asp:TextBox ID="txtHeader" runat="server" />
</p>
<asp:Button ID="btnChangeHeader" runat="server" Text="Change Header" 
onclick="btnChangeHeader_Click" />
</ContentTemplate>
</asp:UpdatePanel> 

4. Call the MasterPage method from content page.
protected void btnChangeHeader_Click(object sender, EventArgs e)
{
Master.ChangeWebsiteHeader(Server.HtmlEncode(txtHeader.Text));
}

Summary:
In this blog we have seen how can we update the master page from the content page using ajax update panel. You can download the source code from here


1 comment: