This post is a result of a question that I got from one of the developers that I work with. The question was how to use master page properties from an ASP.NET page.
Setting the Environment
The first thing that you want to do is to expose the properties as public in the master page. For example this is code behind of a simple master page that exposes the IsPageEnabled property:
01.public partial class Site1 : MasterPage
02.{
03.#region Properties
04.
05.public bool IsPageEnabled { get; set; }
06.
07.#endregion
08.
09.#region Page events
10.
11.protected void Page_Load(object sender, EventArgs e)
12.{
13.}
14.
15.#endregion
16.}
The @MasterType Directive
When we want to use the property in a page which reference the previous master page we need to put the inside of it the MasterType directive:
<%@ MasterType VirtualPath="~/Site1.Master" %>
This directive declare that the master page of a page is strongly type. By that simple directive we gain access to the master exposed public properties and methods through the Master property of the page. For example this is how in the page I’ll call the IsPageEnabled property of the master page:
01.public partial class WebForm5 : Page
02.{
03.#region Page Events
04.
05.protected void Page_Load(object sender, EventArgs e)
06.{
07.Master.IsPageEnabled = true;
08.}
09.
10.#endregion
11.}
The markup of the page I use:
1.<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true"
2.CodeBehind="WebForm5.aspx.cs" Inherits="TestModalDialog.WebForm5" %>
3.
4.<%@ MasterType VirtualPath="~/Site1.Master" %>
5.<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
6.</asp:Content>
Summary
Lets sum up, when we use master pages we can expose properties and methods for the pages. We use the MasterType directive in the page in order to create a strong type master page inside of it. By doing that we can pass data from the page to its master. Very easy and very useful.