Thursday, November 26, 2009

Usage of @MasterType

The @MasterType Page Declarative of a page is used to access the public properties and methods of a master page to the sub level of content page

Example :

Step 1:
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage_MasterPage" %>

<title>ScriptManager in Master Page Example</title>


<form id="form1" runat="server">
<div>
<asp:scriptmanager id="ScriptManager1" runat="server">
<asp:panel id="MasterPanel1" runat="server" groupingtext="Master Page">
<asp:button id="Button1" runat="server" text="Full Page Refresh">
<asp:button id="Button2" runat="server" text="Refresh Panel" onclick="MasterButton2_Click">
</asp:button>
<asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
</asp:contentplaceholder>
</asp:button></asp:panel></asp:scriptmanager></div>
</form>



Step 2:

Create a public property in the MasterPage.master.cs

public partial class MasterPage_MasterPage : System.Web.UI.MasterPage
{
public DateTime LastUpdate
{
get
{
return (DateTime)(ViewState["LastUpdate"] ?? DateTime.Now);
}
set
{
ViewState["LastUpdate"] = value;
}
}
}


Step 3:

Define the <%@ MasterType %> like this

<%@ Page Language="C#" MasterPageFile="~/MasterPage/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="MasterPage_Default" Title="Untitled Page" %>

<!--define like this-->

<%@ MasterType VirtualPath="~/MasterPage/MasterPage.master" %>



<asp:content id="Content1" contentplaceholderid="ContentPlaceHolder1" runat="Server">
<asp:panel id="Panel2" groupingtext="ContentPage" runat="server">
<asp:updatepanel id="UpdatePanel1" updatemode="Conditional" runat="server">
<contenttemplate>
<p>
Last updated: <strong><%= Master.LastUpdate.ToString() %></strong>
</p>
<asp:button id="Button3" text="Refresh Panel" onclick="Button3_Click" runat="server">
</asp:button>
</contenttemplate>
</asp:updatepanel>
</asp:panel>

Step 4:

Then we can use to access the public methods and properties from master page to content page.

protected void Button3_Click(object sender, EventArgs e)
{
Master.LastUpdate = DateTime.Now;
}

No comments: