MasterPage in ASP.NET 2.0


In ASP.NET 2.0 we have a concept called Master Pages which are used to give uniform look and feel for the entire application.

How can we access the methods and properties defined in the Master Page?

The only way to access the master page object model is through the Master property.The Master property of the Page class references the master page object for the content page.This means that only public properties and methods defined on the master page class are accessible with a prerequisite of adding @MasterType directive in the Content Pages.  Suppose we have a protected control in a Master Page how can we access the control in the Content Pages?

 Let us assume we have a label control in the master page whose protection level makes it inaccessible from the outside world.In the master page we can write the code as follows. 

public partial class Simple : System.Web.UI.MasterPage

{   

protected void Page_Load(object sender, EventArgs e) 

   {    }    

 public string LabelText   

 {        

 get { return Label.Text;}       

 set { Label.Text = value;

}   

}

}

 In the content pages (which have Simple as the Master Page) if you do like this, the code will not get compiled. 

public partial class HelloMaster : System.Web.UI.Page

{   

protected void Page_Load(object sender, EventArgs e)

    {       

 Master.LabelText = “Programming ASP.NET-version 2.0”;   

}

} 

Because the Master property is defined of type Master Page. As such it doesn’t know anything about the methods or properties specific to a particular Master. This can be resolved by adding a @MasterType directive in the content page .The @MasterType informs the compiler about the real type of the Master property. The Master property is declared of the right type in the dynamically created page class, and this allows you to write strong-typed code. 

<%@ Page Language=”C#” MasterPageFile=”Simple.master”    CodeFile=”HelloMaster.aspx.cs” Inherits=”HelloMaster” %><%@ MasterType VirtualPath=”Simple.master” %>

Advertisements
This entry was posted in ASP.NET. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s