Introduction
In this article, we will explore the Master Pages feature of ASP.Net 2.0. At the detail level, the article enumerates the usage and the programmatic manipulation of Master Pages.
Some of the examples are basic and have been created for demonstrating simple concepts. The logic can be extended and/or modified to provide functionality in real life scenarios.
We will go through the following topics in the article.
- Master Page Concepts
- Master Page Details
- Options for specifying the Master Page
- Access Master Page Properties
- Event Binding
- Specifying the Master page dynamically
- Nested Master Pages
- Device Specific Master Pages
Master Page Concepts
- Used to Define a consistent look and feel for a website
- Provides a re-usable, easy to manage mechanism to build the site layout.
- Allows developers to design the master page and provide "place holders" for the content.
- Approach similar to "fill-in-the-blanks"
- Content pages use the shell designed with the master page layout and content can be plugged-in to the Content controls.
- WYSIWYG support for designing content pages- the layout defined in the master page is displayed in the content page and the designer can review the content pages at design time.
Details
Master pages are created to define common layout and include ContentPlaceHolder controls. Content pages provide content that is merged into the Master page layout and rendered to the user.
Master Page
This forms the template that defines the layout of the pages. Master pages have an extension .master, and include the @Master directive. Master pages can contain top-level html tags (such as html, head, form) controls, static text and replaceable contentplaceholder controls.
The Master directive:
<%@ Master Language="VB" %>
<%@ Master Language="C#" %>
The Master directive can have the same attributes as the @Control directive.
To create a master page in Visual Studio: Create a new item of type Master page.
Content Page
Content pages provide the content that's plugged in to the layout defined by the master page. Content pages can be tied to a single master page (at a given time, for a given target device) and can include only Content controls. Content pages cannot include any content outside the Content controls. Content pages can include only the Content controls corresponding to the ContentPlaceHolder controls defined by the specified master page. If a Content control corresponding to a ContentPlaceHolder in the master file is not included in the content file, the default content included in ContentPlaceHolder is included in the final merged page.
Content Pages:
- Cannot include top level html elements.
- Can be located in a different folder than master page.
- Can be in a different language than the master
To create a content page: Select new Content page. Visual studio allows to select the Master page.
Content control: The content control is not available in the toolbox. Content controls are derived from specified master page.
Options for specifying the Master Page
1. Page level: The master page for each content page can be specified in the @Page directive
2. Site level: The master page can be specified in the Web.config file - all pages within sites will inherit from the same master
<pages masterfile="sitemaster.master" />
3. Folder level: Specified in the Web.config for that sub-folder
4. Dynamically: The master page can be modified at run time in the Pre-Init event of the Content Page.
Page.Master property: references the specified master page.
Example 1: Master-Content pages.
Files:
- CompanyMaster.master: Master Page
- HomePage.aspx: Content Page
CompanyMaster.master: Master file
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="CompanyMaster.master.cs" Inherits="CompanyMaster" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server" ID="Head1" NAME="Head1">
<title>Company Master</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table width="100%">
<tr bgcolor="gray">
<td align="right">
<b>Welcome to Master Company</b>
</td>
</tr>
<tr>
<td>
<asp:contentplaceholder id="AllContent" runat="server">
This page is under construction.
</asp:contentplaceholder>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Figure: Master Page (Design Mode)
HomePage.aspx: Sample Content page (based on CompanyMaster.master)
<%@ Page Language="C#" MasterPageFile="~/CompanyMaster.master" AutoEventWireup="true" CodeFile="HomePage.aspx.cs" Inherits="HomePage" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="AllContent" Runat="Server">
<b>Welcome to Master Company.</b> <BR />
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Curabitur diam orci, consequat vel, pretium ut, placerat a, sapien. Mauris molestie velit et wisi. Proin venenatis suscipit est. Vivamus eu lorem sit amet dolor tristique rutrum. Nulla nisl. Curabitur scelerisque risus at turpis. Proin lectus erat, ornare sed, cursus at, egestas ut, nunc. Maecenas malesuada risus sed arcu. Suspendisse a nunc. Proin sem lectus, fringilla vitae, dapibus a, suscipit nec, eros. </p>
</asp:Content>
Figure: Content Page (Design Mode): Note the master page layout appears and is grayed out in the content page design

Figure: Results: Note the contents specified in the Content page are merged with the layout specified on the master page. The master page layout can be re-used across the site, to provide a consistent user interface.
How to access Master page properties from the Content page.
Public properties defined in the master page can be accessed as follows.
Cast the Page.Master property to the actual master page type and then access the public property defined in the master page.
Use the MasterType directive to cast the value of the Page.Master property to the specific Master page type and access the properties defined by the master page directly.
Example 2: Access Master page properties
Case 1: Cast the Page.Master property to the type of the Master file and access the public properties exposed by the Master.
Files:
- CompanyMaster.master
- CompanyMaster.master.cs
- HomePage.aspx
- HomePage.aspx.cs
CompanyMaster.master
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="CompanyMaster.master.cs" Inherits="CompanyMaster" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server" ID="Head1" NAME="Head1">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table width="100%">
<tr bgcolor=<%= TopBarBackColor %>>
<td align="right">
<b>Welcome to Master Company</b>
</td>
</tr>
<tr>
<td>
<asp:contentplaceholder id="AllContent" runat="server">
This page is under construction.
</asp:contentplaceholder>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
CompanyMaster.master.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class CompanyMaster : System.Web.UI.MasterPage
{
private string m_strTopBarBackColor = "gray";
public String TopBarBackColor
{
get
{
return m_strTopBarBackColor;
}
set
{
m_strTopBarBackColor = value;
}
}
}
Homepage.aspx: Cast the Page.Master property to the actual master page type and then access the public property defined in the master page.
<%@ Page Language="C#" MasterPageFile="~/CompanyMaster.master" AutoEventWireup="true" CodeFile="HomePage.aspx.cs" Inherits="HomePage" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="AllContent" Runat="Server">
Welcome to Master Company. <BR />
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Curabitur diam orci, consequat vel, pretium ut, placerat a, sapien. Mauris molestie velit et wisi. Proin venenatis suscipit est. Vivamus eu lorem sit amet dolor tristique rutrum. Nulla nisl. Curabitur scelerisque risus at turpis. Proin lectus erat, ornare sed, cursus at, egestas ut, nunc. Maecenas malesuada risus sed arcu. Suspendisse a nunc. Proin sem lectus, fringilla vitae, dapibus a, suscipit nec, eros. </p>
</asp:Content>
HomePage.aspx.cs
using
System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class HomePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
((CompanyMaster)this.Master).TopBarBackColor = "green";
}
}

Figure: Manipulate Master page properties from the content page.
Case 2: Use the MasterType directive to cast the value of the Page.Master property to the specific Master page type and access the properties defined by the master page directly.
Homepage.aspx:
<%@ Page Language="C#" MasterPageFile="~/CompanyMaster.master" AutoEventWireup="true" CodeFile="HomePage.aspx.cs" Inherits="HomePage" Title="Untitled Page" %>
<%@ MasterType VirtualPath="~/CompanyMaster.master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="AllContent" Runat="Server">
Welcome to Master Company. <BR />
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Curabitur diam orci, consequat vel, pretium ut, placerat a, sapien. Mauris molestie velit et wisi. Proin venenatis suscipit est. Vivamus eu lorem sit amet dolor tristique rutrum. Nulla nisl. Curabitur scelerisque risus at turpis. Proin lectus erat, ornare sed, cursus at, egestas ut, nunc. Maecenas malesuada risus sed arcu. Suspendisse a nunc. Proin sem lectus, fringilla vitae, dapibus a, suscipit nec, eros. </p>
</asp:Content>
Homepage.aspx.cs
using
System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class HomePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Master.TopBarBackColor = "green";
}
}
Alternatively, use Master.FindControls method to "find" and reference the controls declared in the Master page. (title, meta etc)
CompanyMaster.master
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="CompanyMaster.master.cs" Inherits="CompanyMaster" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server" ID="Head1" NAME="Head1">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table width="100%">
<tr runat="server" id="Master_TopBar">
<td align="right">
<b>Welcome to Master Company</b>
</td>
</tr>
<tr>
<td>
<asp:contentplaceholder id="AllContent" runat="server">
This page is under construction.
</asp:contentplaceholder>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Homepage.aspx.cs
........
((HtmlTableRow)Master.FindControl("Master_TopBar")).BgColor = "blue";
..........
Attributes of the Html Header in the Master file can be exposed via the HtmlHead element by setting the head tag as a server side control (runat=server)
The following properties of the HtmlHead element are available: LinkedStyleSheets, MetaData, Title, StyleSheet.
The header properties can be accessed in the following format: Master.Page.Header.Title = "...";
Event Binding
Events for controls included in the master are raised in the master page, events for controls included in the content are raised in content page. Page events are raised in both the master page and the content page. The order of events is the same as that for user controls.
Managing Resources
The Content page is merged with the Master page. The Page.CurrentExecutionFilePath property returns the content page at run time.
Managing External resources: Paths are evaluated relative to the content page. If the control is included in the master page, is a server side control, then any URL property is translated to the right path by the system.
Dynamic Master
The master for a content page can be specified in the Pre-init event handler in the Content Page.
In a real life scenario, the user's selection for the layout would be saved in the Profile and the master page would be dynamically set within the PreInit event handler of the content page. If the master page is changed at run-time, the requested content page needs to be reloaded.
Example 3: Dynamic Master: This file uses the CompanyMaster.master files specified above. New files are added as below.
PartnerMaster.master
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="PartnerMaster.master.cs" Inherits="CompanyMaster" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server" ID="Head1" NAME="Head1">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table width="100%" height="80%">
<tr height="100%">
<td valign="top" bgcolor="gray" >
<b>Partner Company</b>
</td>
<td>
<asp:contentplaceholder id="AllContent" runat="server">
This page is under construction.
</asp:contentplaceholder>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
HomePage.cs: modify the master for the homepage from to PartnerMaster.master
protected void Page_PreInit(object sender, EventArgs e)
{
MasterPageFile = "PartnerMaster.master";
}

Figure: Dynamically specified Master page example.
Nested Masters
Master Pages can be nested. Nesting is achieved by specifying the MasterPageFile attribute in the @Master directive.
GUI editing support is not available for nested master files.
Example: Nested Masters example
(Content Page using DeptMaster.master)
<%@ Page Language="C#" MasterPageFile="~/DeptMaster.master" AutoEventWireup="true" CodeFile="DeptHomePage.aspx.cs" Inherits="DeptHomePage" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="DeptContent" Runat="Server">
Welcome to ABC Department.
</asp:Content>