10/26/10

Access Master Page Properties from Content Pages using MasterType

In some cases, it may be necessary to allow a content page to set a master page UI element value. This can be achieved by using the page directive @ MasterType.  This creates a strongly typed reference to the ASP.NET master page.

Scenario:

The master page has  a label control (lblMessage). This label is used by each content page to show a different welcome message. In the master page code behind, add public property as follows:

public string Message 

  get   
  {
     return lblMessage.Text; 
  } 
  set 
  {
    lblMessage.Text = value;
  }


On the content page, add the following directives:

<%@ Master Language="C#" Inherits="~/SiteMaster.master" %>

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

Once the MasterType declaration has been added, you can now access the properties of the master page using the Master class. On the code behind of the content page, add the following code segment:


 
//i.e. on the onload event
Master.Message = "Welcome to my content";

Thanks for reading




og-bit.com