Working with Master Pages


The final section of this chapter looks at a specific feature you can take advantage of when building Web pages and Web sites. You can create a Master Page that contains the boilerplate content for the site and then use this Master Page as the "container" for other pages. These other pages, generally referred to as Content Pages, display within the Master Page. You can have more than one Master Page in your site, though a Content Page can only specify one Master Page. You can also nest Master Pages so that a Content Page can specify a Master Page that in turn specifies another Master Page.

However, bear in mind that Visual Studio will not be able to create a Design View representation if you use a nested Master Page. You may find it is easier to build pages that use only a single Master Page, and thenonce ready to deploy your siteadd the directives that include nesting inside the parent Master Page. You can always remove them again for editing, and reinstate them for redeployment.

You saw a Master Page used to create the overall design of the fictional Adventure Works Web site in Chapter 2.


The two properties of the Page class that support Master Pages are:

  • Master, which returns a reference to the Master Page for the current Content Page or Master Page

  • MasterPageFile, which sets or returns the file name of the Master Page for the current Content Page or Master Page

You can also specify the Master Page for a complete Web site, or for specific folders within the site, by setting the masterPageFile attribute of the <pages> element in the <system.web> section of Machine.Config or Web.Config.

Simple Master Pages

Master Pages are a good way to produce a consistent look and feel for a site, and make it easy to update the appearance of the complete site simply by editing or changing the Master Page. Figure 9.9 shows how a Master Page file (MySite.master) that defines content such as the page header and left-hand navigation menu also contains a ContentPlaceHolder control. The two Content Pages (Page1.aspx and Page2.aspx) reference this Master Page through the MasterPageFile attribute of the @Page directive (this sets the MasterPageFile property).

In Content Pages, the only content permitted is one or more ASP.NET Content controls, each of which uses the ContentPlaceHolderID attribute to specify the ContentPlaceHolder where it displays. In Figure 9.9, only one ContentPlaceHolder control occurs on the Master Page, and there is one Content control on each Content Page. You can use more than one provided that they have matching ID and ContentPlaceHolderID values. If you do not provide a Content control in a Content Page for a ContentPlaceHolder control that exists in the Master Page, any content declared within the ContentPlaceHolder control (called default content) displays instead.

Nested Master Pages

For more complex sites and requirements, you can use more than one Master Page and specify which Master Page each Content Page will use. In Figure 9.10, there is a single root Master Page (BigCorp.master) and two other Master Pages (Sales.master and Research.master). However, the latter are nested Master Pages. They contain the @Master directive (instead of the @Page directive), specify the file BigCorp.master as their Master Page, and have a ContentPlaceHolder control for other Content Pages to populate. However, this ContentPlaceHolder control is within a Content control that references the ContentPlaceHolder control in the BigCorp.master Master Page.

Figure 9.9. Using a single Master Page and two Content Pages


The three Content Pages (in the third row of Figure 9.10) specify which Master Page they use and contain a Content control that points to the ContentPlaceHolder control on the Master Page they will populate. The left-hand and right-hand Content Pages populate the ContentPlaceHolder control in the two nested Master Pages. These ContentPlaceHolder controls are within a Content control on that Master Page, which is then used to populate the "root" Master page (BigCorp.master). You can see in the last row in Figure 9.10 how this results in the final output containing a combination of the Master Page content and Content Page content.

Figure 9.10. Using multiple nested Master Pages


Dynamically Setting the Master Page

Another feature of Master Pages is the ability to choose one dynamically at runtime. One approach is to specify different Master Pages for different types of browsers or user agents. You just prefix the MasterPageFile attribute in the @Page directive with the alias of the browser type that you want to use this Master Page (providing that there is an alias in the configuration for this browser type). For example, if you have a Master Page you want used only for Mozilla browsers, while other browsers use the default Master Page, you would use:

<@Page MasterPageFile="Standard.master"        mozilla:MasterPageFile="Mozilla.master"... />


Another way is to set the MasterPageFile property of the page in code. However, you must do this in the PreInit event of the Page class, as shown in Listing 9.19, and not in any later events such as the Load event.

Listing 9.19. Selecting a Master Page Dynamically at Runtime

protected void Page_PreInit(object sender, EventArgs e) {   Page.MasterPageFile = "~/MyNewMasterPage.master"; }

Accessing Values and Controls in the Master Page

Master Pages provide a great solution to separating out boilerplate content and page-specific content. However, the Master Page is likely to contain controls and values that you need to access from within the Content Pages. An example is the samples viewer that we provide to allow you to run the examples available for this book. As you load each example page, code in the Master Page changes the display of the colored tabs at the right-hand side of the page to reflect the current chapter number. This means that the Master Page needs to know the current chapter number each time the user loads a page.

Every page you see in the samples viewer specifies the Master Page file named Examples.master in the root folder of the site. Listing 9.20 shows a section of the partial code-behind class (Examples.master.cs) that implements the Master Page. You can see that it declares a public property named CurrentChapter.

Listing 9.20. The CurrentChapter Property Exposed by the Master Page

public partial class Examples : System.Web.UI.MasterPage {   // public property   Int32 mCurrentChapter;   public Int32 CurrentChapter   {     get { return mCurrentChapter; }     set { mCurrentChapter = value; }   } ...

Listing 9.21 shows the @Page directive for the page Default.aspx, and you can see the MasterPageFile attribute that specifies the Master page Examples.master. Notice that a @MasterType directive also specifies this Master Page file.

Listing 9.21. The @Page Directive Specifies the Master Page File

<%@ Page Language="C#"MasterPageFile="/Examples.master"          AutoEventWireup="true"CodeFile="Default.aspx.cs"          Inherits="_Default"%> <%@ MasterType VirtualPath="~/Examples.master"%>

The code in the Default.aspx page, implemented as a partial codebehind class in the file Default.aspx.cs, looks for a "current chapter" value in the query string as the page loads. If it finds one, it sets the CurrentChapter property in the Master Page to this value by referencing it through the Master property of the Page class (see Listing 9.22).

Listing 9.22. Setting the CurrentChapter Property in the Master Page

protected void Page_Load(Object sender, EventArgs e) {   // update chapter number in master page   // through the public property it exposes   CurrentChapter = 0;   if (Request.QueryString["ch"] != String.Empty)   {     try     {       CurrentChapter = Int32.Parse(Request.QueryString["ch"]);       Master.CurrentChapter = CurrentChapter;     }     catch { }   } ...

One point to watch out for is that some objects that are properties of the page are not actually available in the Page_Load or other events of the Master Page. For example, the current User object instance object is not attached to the page until construction of the Master Page is complete, and so cannot be accessed directly from the Master Page. However, you can usually get a reference to objects in code within the Master Page through the current ASP.NET context; for example, you can get the current user name like this:

String name = HttpContext.Current.User.Identity.Name;


If you want to access a control on a Master Page from a Content Page, you can expose a reference to the control as a property of the Master Page, as shown in Listing 9.23. Then, in the Content Page, you can set the text in the label control using Master.MyLabelCtrl.Text = "My new value";.

Listing 9.23. Exposing a Control as a Property in a Master Page

// public property to access control named MyLabelCtrl public Label MyLabelCtrl {   get { return TheLabelControl; } }

An alternative approach is to use the FindControl method of the Page class to search the Controls collection of the Master Page. This is a late-binding technique, which is not as efficient as the early-binding approach you just saw. However, it does mean that you do not have to expose the controls as properties in the Master Page. As an example, you could access the Label control in the Master Page that has ID value MyLabel from a Content Page using:

Label ctl = Master.FindControl("MyLabel") as Label;


Remember that controls in a Content region of a Content Page replace controls in the associated ContentPlaceHolder region on the Master Page. Therefore, if both the Content and ContentPlaceHolder controls contain a Label control, accessing that Label from server code in the Content Page will actually access the Label from the Content Page, and not that of the Master Page.




ASP. NET 2.0 Illustrated
ASP.NET 2.0 Illustrated
ISBN: 0321418344
EAN: 2147483647
Year: 2006
Pages: 147

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net