Welcome!

.NET Authors: Michael Bushong, Tad Anderson, Ivan Antsipau, Liz McMillan, Pat Romanski

Related Topics: .NET

.NET: Article

Master Pages in ASP.NET 2.0

Simplify reuse and maintenance

Since the advent of Web development, Web developers have sought a way to provide a consistent look and feel across the Web application. This pursuit has resulted in different custom solutions. With the introduction of master pages in ASP.NET 2.0, Microsoft has finally brought the support to the framework level and has given the developers what they have been asking for. Master pages, as the name suggests, allow the developer to define the layout in a single page and easily apply the layout to multiple pages across the Web site, thereby ensuring a consistent appearance. This article looks at how we use master pages with the help of some examples. We will also look at some of the new features that are available in ASP.NET 2.0.

Master Pages
Master pages allow the developer to take a compartmentalized approach while developing Web sites. It allows the developer to move standardized layouts like header, footer, navigation, or any other content that is common over multiple pages to the master page. Content that is specific to a particular page can be defined in content pages that we will see in the next section. Master pages are transparent to the users and when a request is made to the URL of the content page, ASP.NET merges the content of the content page with that of the master page and renders the resulting page. Unlike ordinary ASPX pages, a Web server does not serve a master page and if a user makes a request to the master page, the server returns an error message (see Figure 1).

Master pages are like any other ASP.NET pages with a couple of exceptions. They are identified by a .master file extension. Listing 1 (the code is online at www.sys-con.com/dotnet/source.cfm) is an example of a simple master page. Note that instead of the familiar page directive <%@Page%> in a normal ASPX page, the master page has a <%@Master %> directive. Master pages define ContentPlaceholder controls that act as placeholders where content from the content page will be inserted. ContentPlaceholder control is specific to master pages and cannot be declared in a content page. In this example we have defined one ContentPlaceholder control identified as ContentPlaceholder1. A master page can define zero to any number of ContentPlaceholder controls.

Content Pages
The content page is the actual page that a user will request from the server. Content pages are like typical ASPX pages and have a .ASPX extension. However, they differ from an ordinary ASPX page in two ways. The first difference is that a content page has to be associated with a master page, which is done by setting the MasterPageFile attribute in the page directive. Second, all of the content in a Web page must be defined inside a new content control. Any content that is defined outside the content control results in an error. The content control in turn has to be mapped to the Contentplaceholder controls that have been defined in the Master page. Listing 2 shows a content page that refers to Sample.master as its master page. In this example the content page defines a content control called Content1. This content control in turn is mapped to the ContentPlaceholder ContentPlaceHolder1 of the master page by setting the ContentPlaceHolderID.

Sequence of Events
Just like regular ASPX pages, master pages and content pages have events that are fired during the page life cycle. They can also have user controls that need to be initialized. The list below shows the sequence of events in a content page that references a master page.

  1. Controls in the master page are initialized
  2. Controls in the content page are initialized
  3. Master page is initialized
  4. Content page is initialized
  5. Content page loads
  6. Master page loads
  7. Master page controls load
  8. Content page controls load
Creating a Master Page and a Content Page
Now that we have seen what a master page and a content page are, let's see how to create a master and content page using Visual Studio .NET 2005 Beta. Visual Studio allows us to add master pages by choosing an item of type Master Page in the Add New Item option. It also gives us the option to have a code behind page associated with the master page and also select the language of the page. In Figure 2, I add a master page called MyMaster1.master using the Add New Item dialog.

To the master page that I just created, I have added an image, footer, and two content placeholders. Each of the ContentPlaceholder controls that has been added has a unique ID which will be referred to by the content page to insert its content. Listing 3 shows the markup and Figure 3 shows the design view of the master page that I have created. Any content page that uses this master page will automatically inherit the image, the heading, and the footer.

Now that we have created the master page, let's go ahead and create a content page using the Add New Item option in Visual Studio .NET 2005 Beta (see Figure 4). A content page is just an ordinary Web form and Visual Studio .NET 2005 Beta does not have a special type called content page. When we create the content page, the Add New Item dialog, however, gives us the option to select the master page that will be referenced by the Web form. Once we select this option, Visual Studio presents us with a dialog box that lists all the master pages in the Web site (see Figure 5). Figure 6 shows the design view of the content page that we have just created. You will notice that all the master page content is grayed out and cannot be edited. Listing 4 shows the markup of the content page we just created. The only editable portion in the content page is between the <asp:Content> tags. Each of these content tags is linked to ContentPlaceholder of the master page by setting the ContentPlaceHolderID for the content control. In Listing 4, Content1 is mapped to ContentPlaceholder1 of the master page and Content2 is mapped to ContentPlaceholder2 of the master page. Content control in turn can contain other controls. In this example I have added some text in each of the content tags. Figure 7 shows the browser rendering of the content page.

Nesting Master Pages
Master pages can be nested and can have one master page refer to another as its master. Nested master pages are very useful while designing Web sites with different sections where each individual section has to have its own layout and at the same time be consistent with the overall appearance of the Web site. For example, in a corporate Web site we could have a master page that could define the global menu and a master page for each department that would define the departmental menu. Nesting the department master page and the corporate master page would allow us to combine the two menus. Visual Studio .NET 2005 Beta, however, does not provide designer support for nested master pages.

Let's look at how to create a nested master page with the help of an example. Listing 5 shows the parent master page, ParentMaster.master. This parent master page is then referred to by the child master page (see Listing 6). As you can see, the child master page is not very different from the parent master page. They have the same .master extension; however, the child master page has a content control that is mapped to the ContentPlaceHolder control defined in the parent master page. The child master page can also define ContentPlaceHolder controls of its own to display content of the content page that refers to this page as its master. The child master page in our example defines a content control that is mapped to ContentPlaceHolder1 of the master page. It defines a Contentplaceholder control of its own ChildContentPlaceHolder1 to which the content page will map its content. Listing 7 is the content page that refers to the child master page as its master page. Figure 8 shows the rendering of the content page that uses nested master pages.

Configuring a Site to Use Master Pages
Instead of giving the master attribute in the page directive of each and every page in a Website, ASP.NET 2.0 gives you the option to set the master page in the Web.config file. This is very useful in large Web sites as it gives the developers the flexibility to make the change at one place and apply it across the site. The code snippet below shows how to set the master page in the web.config file:

<system.web>
<pages masterPageFile="MyMaster1.master" />
</system.web>

A couple of things need to be pointed out about setting master pages through the web.config file. First, if the content page has a master page explicitly set in its page directive, that master page assumes precedence over the one set in the web.config file. If there are multiple master page settings in different web.config files, the master page setting in the immediate folder overrides the other setting similar to how in an application with multiple sub- folders, the setting of the web config in the immediate folder takes precedence over the others.

Accessing Master Page Controls from Content Pages
The developer may need to access the controls in the master page for many reasons. One could be to display a value that is relevant to the content page. ASP.NET 2.0 gives you multiple options to achieve this. The first step is to get a reference to the master page. In a content page, the Master property returns the reference to the master page. Once we have obtained the reference to the master page, it is now possible to refer to the controls of the master page. We will look at two approaches. The first approach is early binding, where the control is declared as a public property in the master page. Listing 8 shows the master page where we first expose the text of control Label2 as a public property LabelText. We then access and set the value of LabelText in the page load event of the content page as shown in Listing 9. Another thing to point out is the strong typed reference to the Master page using the <%@masterType%> directive in the Content page. This explicitly casts the value of the master property to the master page object which in our case is AccessMasterProperties.

The second approach is the late binding approach. Here we make use of the familiar FindControl method. We get a reference to a label control in the master page and change the text value from the content page. We search for the label by its ID which in this case is Label1 and then cast it to a label control and set the value for the text.

Dynamically Changing Master Pages
ASP.NET 2.0 allows the developer to change the master page associated with a content page dynamically at run-time. This is very useful if the developer would like to give the users the flexibility of choosing the master pages. The master page for a content page can be set programmatically by assigning a value to the MasterPagefile property of the page. However, this dynamic assignment can be done only in the preinit event of the content page since this is the earliest event that occurs in the page execution life cycle. If we attempt to set the master page file in events like pageload, it would result in an exception. Listing 10 shows an example where we have a dropdown list with the available master pages. On clicking the button we redirect the response to the same page and pass the value of the master page to be set as a request string. The MasterPagefile is then set in the preinit event.

Device-Specific Master Pages
ASP.NET 2.0 pages and controls have built-in support that enables them to automatically render appropriate content depending on the browser and the device that has requested the page. Master pages also support similar behavior. We can create a master page specifically for a device or a browser and in the content page instead of binding to a single master page. We can bind them to number of master pages, each of them specific to a particular device. The binding is qualified with the device name. Listing 11 shows a content page that is bound to two master pages, one for Internet explorer and another for mozilla. The Internet Explorer master page is prefixed with ie and the one for Mozilla is prefixed with Mozilla. These browser prefixes are defined in the browsercaps section of the machine.config file. Depending upon the browser requesting the page, the content page is bound to the appropriate master page. Figures 9 and 10 show the rendering of the content page when it is requested through the two different browsers, Mozilla and Internet Explorer. As you see, ASP.NET 2.0 has automatically chosen the appropriate master page.

Conclusion
In this article we looked at the concept of master pages and saw how they allow the developer to easily create reusable page layouts. It also greatly simplifies maintenance as it is now possible to make changes at one place and propagate them throughout the Web site. I am sure that this feature will have a significant impact on how ASP.NET applications are built in the future.

More Stories By Jeevan Murkoth

Jeevan Murkoth is a Microsoft Certified Solutions Developer (MCSD) in .NET (Early Achiever) and a Microsoft Certified Application Developer (MCAD) in .NET. He currently consults for Tennessee Valley Authority and lives in Chattanooga, TN. He has an MS in Management Information Systems from Texas Tech University.

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Mujtaba Syed 12/14/04 03:48:48 PM EST

Nice article.