Resources

Using Master Pages in ASP.NET sites

A master page is a single file that controls layout of all pages within site. Master pages make website more consistent and easier to maintain.

Themes centralise settings that define appearance of site, allow change of appearance to every page with single update.

Caching improves site responsiveness, reduce CPU load, decrease file and database I/O.

Using Master Pages

Modern website design demands consistent site layout. Typically logo in top left. Search box in top middle or right. Below this are navigational links. At bottom of page are copyright and contact information.

Can use Master Pages to provide common structure to all pages in site.

Overview

Have .master extension

Very similar to .aspx pages

Contain text, HTML and server controls.

Inherits from MasterPage class, rather than Page class.

Have @Master directive at top of page, rather than @Page

Processing order...

  1. User requests page
  2. Page is fetched and @Page directive is read. If it references a master page then the master page is read as well. If this is the first time the page has been requested then both are compiled
  3. Master page and updated content merged into control tree of content page
  4. Each Content control is merged into corresponding ContentPlaceHolder control in master page
  5. Merged page is rendered to browser as single page

Creating Master Page

Create via Add New Item dialogue.

Layout in same way as any .aspx page - can add tables, styles, etc. to define page.

Frequently have empty <title> element in header - pages using the master sheet can specify it via the title attribute in @Page directive.

ContentPlaceHolder controls allow the pages using the master page to insert content into the page. For example:

<head runat="server>

<title></title>

<asp:ContentPlaceHolder ID="HeadContent" runat="server"/>

</head>

<body>

<h1>Contoso, Inc.</h1>

<asp:ContentPlaceHolder ID="MainContent" runat="server"/>

</body>

defines two place holders. One can be used to insert content into the <head> of the document, the other into its <body>.

Creating Content Pages

To add to web site project select "Select Master Page" check box in "Add New Item" dialogue.

To add to web application project select "Web Forum Using Master Page" from "Add New Item" dialogue.

Alternatively, associate .aspx page to a master page using MasterPageFile attribute in @Page directive.

Provides mark-up for ContentPlaceHolder controls in master page, e.g.

<%@ Page MasterPageFile="site.master" ... %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceholderId="HeaderContent">

...

</asp:Content>

<asp:Content ID="MainContent" runat="server" ContentPlaceholderId="MainContent">

<h2>Log in</h2>

</asp:Content>

In general master page structure has no effect on content pages. If set page-wide property, such as EnableViewState, in master page then will effect content page, e.g. EnableViewState set to true in content, but false in master then it will be false when page generated (master page takes priority).

Attaching Master Page to Content Page

By default associated using the MasterPageFile attribute of @Page directive.

Can define master page for site, application or folder by defining MasterPageFile property of <pages> element in web.config file. Using this approach all pages in scope of config file that have Content controls are merged with specified master page file.

Reference master page properties, etc. from content page

Can use master pages to define application-specific settings on which content pages depend, e.g. many pages need a users login ID which can be set in master page and made available to all:

  1. Create public property in master page code-behind file
  2. Add @MasterType declaration to content page (which sets strong type for master page accessed via Master property)
  3. Reference master page property from content page using syntax Master.<Property_Name>

Minimise dependencies between master and content pages - fewer problems when updating pages and easier to support multiple developers.

When dependency is required make content page reference master, and not other way round.

Can use events to communicate between master and content page. If content page needs to adjust itself based on selection made in master drop down list consider raising event on master page and have content pages subscribe to event.

Creating public property in Master Page

Content pages can reference any public property defined in master page. Can use this to provide strong typing to session variables:

public string SharedInfo
{
get { return (String)Session["SharedInfo"];}

set { Session["SharedInfo"] = value; }
}

Can also apply similar approach to application variables.

Connecting to Master Page properties

Must add @MasterType directive to page, e.g.

<%@ MasterType VirtualPath="~/site.master" %>

After directive added can use Master class to access properties.

If change master page associated with content page, ensure new one implements same public properties.

If creating multiple master pages referenced by same set of content pages, then derive master pages from common base class. Then reference this base class name in @MasterType declaration, e.g. assuming all master pages derive from BaseMasterPage

<%@ MasterType TypeName="BaseMasterPage" %>

Referencing the base class ensures all content pages reference the same properties regardless of the master page they use.

Referencing controls in Master Page

One way is to encapsulate control in a property of master page => clean solution as master page developer is deliberately exposing control and so creating contract with content pages.

Other mechanism is through Master.FindControl() method. Requires content page to have knowledge of master page. The returned control needs to be cast to correct control type. Can then treat control as if it were local to content page.

Nested Master Pages

Every page on site may require logo, search box and copyright information. Online store pages require product category and shopping cart links. Discussion section requires forum navigation and profile management links. In this scenario crate top-level master page and then nest different master pages for store and community sections.

Create child master page via "Add New Item" dialogue and selecting "Select Master Page" check box.

Child master pages still use .master extension. Child master pages include MasterPageFile attribute in their @Master declaration.

Child master page typically contains content controls that map onto content place holders on parent master page - i.e. laid out like any content page. Also has content place holders of its own that define areas where its content pages can place content.

Dynamically changing Master Pages

Change switch to another master page dynamically.

Allows for different templates to be provided to different users, e.g. formatting data for different browser types.

void SP_SelectedIndexChanged(object sender, EventArgs e)
{
Session["masterpage"] = SP.SelectedValue;

Server.Transfer(Request.Path);
}
void Page_PreInit(object	sender, EventArgs e) 
{
if (Session["masterpage"] != null) MasterPageFile = (String)Session["masterpage"];
}

Note use of Server.Transfer to cause page to be reloaded and hence Page_PreInit to be called.

Downloads