Reply to comment

Access Master Page properties from the content page

Many times you need to access a control in your master page from the content page (like setting a page title or adding specific META tags). Most tutorials will show you that you can just use the Page.Master FindControl() method to do something like this:

// get the control by searching the master page collection.
Label lblControlToFind = (Label)Page.Master.FindControl("lblPageTitle");
 
// make sure the control was found.
if (lblControlToFind != null)
{
    // do something with the control.
    lblControlToFind.Text = "My Page Title 1";
}

Here I've created a control on the master page named: 'lblPageTitle' which will display the title that is passed to it as text.



The big problem with this approach is that there is no strong typing so if you were to change the name of the Master page's title control, then this would break at run-time with no compile time checking.

A better approach is to use a master page directive in the HTML of the content page. Just add the following line:

<%@ Page Language="C#" MasterPageFile="~/MasterPage1.master" AutoEventWireup="true" CodeFile="ContentPage1.aspx.cs" Inherits="ContentPage1" %>
 
<%@ MasterType VirtualPath="~/MasterPage1.master" %>

Here I have a master page called "MasterPage1.master" and a content page called "ContentPage1.aspx". Once you add this directive to the top of your content page just under the main page directive, .NET will then understand when you access properties of the master page, that it should use this specific object (which inherits from MasterPage) as opposed to the MasterPage base class.

Now add a public property to the master page to expose the lblPageTitle control's text property like this:

public string PageTitle
{
    set
    {
        // set the lblPageTitle control's Text property to the value passed in.
        lblPageTitle.Text = value;
    }
}

Now you can access this property from the content page like this:

// set the title of this page
Master.PageTitle = "My Page Title 1";

This makes it easy in the Page_Load() event of the content page to do whatever manipulation you want to the master page before the page is rendered. And better still, it is all strongly typed.

Reply