ONDotNet.com    
 Published on ONDotNet.com (http://www.ondotnet.com/)
 See this if you're having trouble printing code examples


Master and Content Pages in Whidbey

by Wei-Meng Lee
12/15/2003

Most web sites you see today have a consistent look and feel, containing a company logo and perhaps a navigational menu. A good example is O'Reilly's web site, where every page has a consistent look with a navigational menu on the left side of the page (see Figure 1):

Figure 1. Most web sites employ a common header and navigational menu

As an ASP.NET web developer, you can use user controls to encapsulate all of the headers and navigational menus and embed them onto every web page. However, if there are modifications to the user controls, it usually involves manually editing every single page to modify its layout.

In ASP.NET Whidbey, there is a new feature known as Master and Content Pages. This feature addresses the limitations of using user controls for headers and navigational menu information. In Whidbey, you can simply construct a Master page to include your page header information. You then build your page normally using Content pages, which will automatically include the header information defined by the Master page. To really understand how Master pages and Content pages work, let's build a simple web site using O'Reilly as an example.

Creating the Master Page

Let's first create a Master page containing some header information and a navigational menu. Launch Visual Studio .NET Whidbey and create a new web site project. In the Solution Explorer, right-click on the web site name and select Add New Item.... Select the Master Page Using Code Separation template and click Open (see Figure 2).

Figure 2. Creating a new Master page

Drag and drop the following controls to the Master Page (see Figure 3):

For this article, name the image control containing the O'Reilly logo "imgTitle". Set the NavigateUrl property of the HyperLink control to "default2.aspx" (I will illustrate how the navigational menu can be changed when the Conferences menu item is clicked).

Figure 3. Populating the Master page

I have saved all the of images that I will use for this article in the Image folder (see Figure 4).

Figure 4. The image folder for storing all of the images

Creating the Content Page

Once the Master page has been created, I will now create the content page that will make use of the Master page representing the header. In Solution Explorer, right click on the web site name and select Add New Item.... Select the Content Page Using Code Separation template and click Open. You will be asked to choose the Master page to use. Select MasterPage.master (see Figure 5). Click Open.

Figure 5. Choosing a Master page for a Content page

You should see your Content page as shown in Figure 6:

Figure 6. The content page with the Master page content embedded

The Content page consists of the header (as specified in the Master Page) and a Content control. The Content control is the placeholder for all other controls on the page. Essentially, this is where your content of the page is located. In our case, I will create two Content pages: one for the main page (see Figure 7) and one for the Conference page (see Figure 8).

Figure 7. The main page (main.aspx)
Figure 8. The Conference page (default2.aspx)

Customizing Individual Pages

With the main page selected (in Solution Explorer), press F5 to start debugging the web application. You should see the following:

Figure 9. Displaying the main page

When the user navigates to the Conference page (by clicking on the Conferences menu item), it will display default2.aspx (but with the O'Reilly logo changed to a conference logo). I also want to change the color of the Conferences hyperlink to yellow, as shown in Figure 10.

Figure 10. The Conference page displayed with the logo and the menu item color changed

To perform the required customization, you need to write code in the code-behind of default2.aspx. Specifically, you need to change the image of the image control (imgTitle) during the Page_Load() event. You would also change the color of the hyperlink control (lnkConference) at this point. Here is the code:

Imports Microsoft.VisualBasic

Namespace ASP
  Expands Class Default2_aspx
    Sub Page_Load(ByVal sender As Object, _
                  ByVal e As System.EventArgs)
      ' change the image
      Dim masterImage As System.Web.UI.WebControls.Image
      masterImage = CType(Master.FindControl("imgTitle"), _
                    System.Web.UI.WebControls.Image)
      If Not (masterImage Is Nothing) Then
        masterImage.ImageUrl = "Image/conference_header.gif"
      End If

      'change the color of the Conferences label
      Dim masterLink As System.Web.UI.WebControls.HyperLink
      masterLink = CType(Master.FindControl("lnkConferences"), _
                   System.Web.UI.WebControls.HyperLink)
      If Not (masterLink Is Nothing) Then
        masterLink.ForeColor = System.Drawing.Color.Yellow
      End If
    End Sub
  End Class
End Namespace

Basically, you locate controls of the Master page by using the FindControl() method of the Master property, supplying the name and type of the control you want to locate. Once the control is located, you can then change its properties as if it were a local object.


Dim masterImage As System.Web.UI.WebControls.Image
masterImage = CType(Master.FindControl("imgTitle"), _
              System.Web.UI.WebControls.Image)
If Not (masterImage Is Nothing) Then
  masterImage.ImageUrl = "Image/conference_header.gif"
End If

The C# equivalent of the above is as follows:

using System;
namespace ASP
{
	public partial class Default2_aspx
	{
		void Page_Load(object sender, System.EventArgs e)
		{
      //change the image
			System.Web.UI.WebControls.Image masterImage;
			masterImage = (System.Web.UI.WebControls.Image) 
			              Master.FindControl("imgTitle");
			if (masterImage != null)
      {
				masterImage.ImageUrl = 
          "Image/conference_header.gif";
      }

			//change the color of the Conferences label
			System.Web.UI.WebControls.HyperLink masterLink;

			masterLink = (System.Web.UI.WebControls.HyperLink)
			  Master.FindControl("lnkConferences");
			if (masterLink != null)
      {
				masterLink.ForeColor = 
          System.Drawing.Color.Yellow;
      }
		}
	}
}

The method that I have just described uses late-binding to access controls on a Master page. There is yet another more efficient way to change the controls in the Master page using early-binding. Using early-binding, the Master page needs to expose public properties so that the Content page can set or access them during runtime.

For example, suppose I want to set a different page title (using the <title> HTML element) for every page. I can declare a property in the Master Page to allow modification of the title of a page during runtime:


<%@ master language="VB" compilewith="MasterPage.master.vb"
           classname="ASP.MasterPage_master" %>
<script runat="server" language="vb">
  Protected pageTitle As String
  Public WriteOnly Property title() As String
    Set(ByVal Value As String)
      pageTitle = Value
    End Set
 End Property
</script>

<html>
  <head runat="server">
    <title><% =pageTitle %></title> 
  </head>
<body>
...

In C#:


protected String pageTitle = "O'Reilly & Associates ";
public String HtmlTitle
{
  set { pageTitle = value; }
}

Note that I have also changed the HTML portion of the page to insert the value of the pageTitle variable into the <title> element. To change the title of the page during runtime, you can access the title property by using the following statement in the Form_Load() event:

me.Master.Title = "O'Reilly & Associates Conferences"

In C#:

this.Master.Title = "O'Reilly & Associates Conferences";

So when the conference page is loaded, you will see the page titled changed (see Figure 11):

Figure 11. Changing the title of a page

Summary

In this article, you have seen how the Master and Content pages allow you to build your web site easily and efficiently. One of the main thrusts of ASP.NET 2.0 is the reduction of the amount of coding needed to write your web application. We will look at some new data controls in Whidbey in the next article.

Wei-Meng Lee (Microsoft MVP) http://weimenglee.blogspot.com is a technologist and founder of Developer Learning Solutions http://www.developerlearningsolutions.com, a technology company specializing in hands-on training on the latest Microsoft technologies.


Return to ONDotnet.com

Copyright © 2009 O'Reilly Media, Inc.