Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Gauge for SharePoint
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » ASP.NET 2.0 » Master Pages in ASP.NET 2.0

Master Pages in ASP.NET 2.0

This article explores 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.

Author Rank :
Page Views : 9088
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Nevron Gauge for SharePoint
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

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>

Figure: Nested Master page example.

Device Specific Masters

Master files can be customized based on the target device. The master file corresponding to the target devices can be specified in the @Page attribute.

Conclusion

In this article, we saw an introduction to the Master Page feature of ASP.Net 2.0. Master Pages provide a template in which content can be plugged into for individual content pages. The Master Page layout and the Content from the Content Pages is merged to produce the final web page. Master Pages provide re-usability and offer a mechanism to standardize the look and feel of the web site. The most common uses of Master Pages would be to define a common banner/side bars for the website, providing common links, menu system and/or search functionality across the website.

The code included in this article has been tested on ASP.Net Beta 2 and may not be compatible with other releases.

NOTE: This article is purely for educational purpose. This article should not be construed as a best practices white paper. This article is entirely original, unless specified. Any resemblance to other material is an un-intentional coincidence and should not be misconstrued as malicious, slanderous, or any anything else hereof.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Dipal Choksi
Dipal Choksi has over 10 years of industry experience in team-effort projects and also as an individual contributor. She has been working on the .Net platform since the beta releases of .Net 1.0.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
No able to get property in content page by Ayaz On July 31, 2006

Hi

I declared public property in Master Page, but not able to get that variable in content page.

 

Please tell me, where i went wrong?

 

Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.