Exposing a property on the master page to child page

Sometimes, when we are using master pages, we have the necessity to access some information that is available “only” on the Master Page, there are a few ways you can expose this information to child pages access them. One way is through Property, lets say that you have on the master page the string attribute  called _userName, but in your child page you need this UserName too, so you can create an property on the MasterPage that return this attribute. This way on the child page we can call this property like this, Master.UserName, only don’t forget to set the directive MasterType in your child page, set the value VirtualPath with the path of you master page.

Master Page


public partial class MyMasterPage : System.Web.UI.MasterPage
{
public virtual string UserName { get {return this._userName;} }
private string _userName;

protected void Page_Init(Object sender, EventArgs e)
{
this._userName= "Douglas";
}
}

MyChild.aspx

<%@ Page Title="MyChild" Language="C#" MasterPageFile="~/Master/MyMasterPage.Master"
AutoEventWireup="true" CodeBehind="MyChild.aspx.cs" Inherits="MyChild" %>
<%@ MasterType VirtualPath="~/Master/MyMasterPage.Master" %>

MyChild.aspx.cs (Code Behind)

public partial class MyChild: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
labelUserName.Text=Master.UserName;
}
}

Reference: http://msdn.microsoft.com/en-us/library/c8y19k6h.aspx

Leave a comment