Master Pages
ASP.NET 2.0 provided a treasure trove of new features. Perhaps none of these generated as much anticipation as master pages. This new feature allows the developer to define the structural layout for multiple Web Forms in a separate file and then apply this layout across multiple Web Forms. You can thus move common layout elements, such as logos, navigation systems, search boxes, login areas, and footers, out of all the individual pages and into a single master page.
Any developer who has had to create and maintain an ASP.NET Web application that consists of more than two or three pages should be able to see the value of this ability. In most Web applications, the individual pages typically share a common structure or a common look and feel across the entire site. For instance, most pages within a site may have a logo in the upper-left corner, a global navigation system across the top, a secondary navigation system down the left side of the page, and a footer at the bottom of the page. It is clearly less than ideal to replicate the markup and code for this common structure across multiple pages.
Master pages provide a solution to this problem. They allow the developer to create a consistent page structure or layout without duplicating code or markup. Master pages are created in much the same way as any other Web Form. They contain markup, server controls, and can have a code-behind class that responds to all the usual page lifecycle events. However, they do have their own unique extension (.master) as well as a different directive at the top of the page. As well (and most importantly), they also contain one or more ContentPlaceHolder controls.
The ContentPlaceHolder control defines a region of the master page, which is replaced by content from the page that is using this master page. That is, each Web Form that uses the master page only needs to define the content unique to it within the Content controls that correspond to the ContentPlaceHolder controls in the master page, as illustrated in Figure 6.9.
Figure 6.9 Master pages
Like any Web server control, each ContentPlaceHolder control within a master page must have a unique Id.
<asp:ContentPlaceHolder id="contentBody" runat="server"> </asp:ContentPlaceHolder>
This Id is used to link the Content controls in the various Web Forms that use the master page. This link is made via the ContentPlaceHolderId property of the Content control.
<asp:Content id="myContent" ContentPlaceHolderId="contentBody" runat="server"> </asp:Content>
A master page significantly simplifies the markup for pages that use it. The master page contains the complete XHTML document structure. That is, the html, head, and body elements are contained only within the master page. The.aspx files that use the master page only need define the content that will be inserted into the placeholders in the master page. In fact, these .aspx files can only contain content within Content controls. Unlike HTML frames (which perform a somewhat similar function in HTML), master pages are transparent to the user (that is, the user is unaware of their existence) because ASP.NET merges the content of the master page with the content of the requested page.
Visual Studio and its designer completely support master pages. You can visually edit the master page, as well as visually edit the individual aspx pages as they would appear within the master page. Figure 6.10 illustrates the BookHome.aspx page within the Visual Studio designer. Only the contents of the Content control are editable; the master page markup is displayed (ghosted out) but cannot be edited.
Figure 6.10 Visual Studio support for master pages
You can specify the master page to use when you add a new Web Form in Visual Studio simply by turning on the Select Master Page option in the Add New Item dialog box (see Figure 6.11).
Figure 6.11 Creating a Web Form that uses a master page
When you choose this Select Master Page option, Visual Studio then displays the Select A Master Page dialog (see Figure 6.12). This dialog displays all the master pages in the Web site (i.e., all the files with the .master extension).
Figure 6.12 Selecting the master page
Of course, you can use a master page in any Web Form without the intervention of Visual Studio simply by adding the appropriate MasterPageFile attribute to the form's Page directive, as shown in the following.
<%@ Page MasterPageFile="~/Books.master" ... Title="Book Home" %>
This example also contains the Title attribute. Because the master page must define the <head> section, you need some way to specify the page title (which is displayed in the browser's title bar) in the individual pages themselves. The Title directive provides one way to do this; the other is to programmatically set the page's Title property. If you do not set it, the page is displayed in the browser with "Untitled" in the title bar.
As an alternative to specifying the MasterPageFile attribute on each Web Form in your site, you can specify it at once globally for all pages in the site via the Pages element in the Web.config file.
<system.web> ... <pages masterPageFile="~/Books.master" /> </system.web>
Note that setting the MasterPageFile attribute in the Web Form overrides the setting in the Web.config file.
Defining the Master Page
As already mentioned, a master page looks like a regular Web Form except that it has a different extension and directive. As well, a master page contains one or more ContentPlaceHolder controls. The following example illustrates a sample master page (the positioning and formatting is contained in its style sheet).
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Site.master.cs" Inherits="Site" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> <link rel="stylesheet" type="text/css" href="~/styles.css" /> </head> <body> <form id="form1" runat="server"> <div id="container"> <div id="header"> <asp:Image runat="server" ID="imgLogo" ImageUrl="~/images/cool.gif" /> </div> <div id="sideArea"> <div id="menu"> <asp:BulletedList ID="blstSample" runat="server" DisplayMode="HyperLink" > <asp:ListItem Value="BookHome.aspx"> Home </asp:ListItem> <asp:ListItem Value="Products.aspx"> Products </asp:ListItem> <asp:ListItem Value="Contact.aspx"> Contact Us </asp:ListItem> </asp:BulletedList> </div> <div id="sideAreaBox"> <asp:ContentPlaceHolder ID="sideContent" runat="server"> <p>default side content</p> </asp:ContentPlaceHolder> </div> </div> <div id="mainArea"> <asp:ContentPlaceHolder ID="mainContent" runat="server"> <p>default main content</p> </asp:ContentPlaceHolder> </div> <div id="footer"> <p> This site is not real. It is an example site for Core ASP.NET book. </p> </div> </div> </form> </body> </html>
Notice that both ContentPlaceHolder controls contain default content. This default content is displayed if the aspx files that use this master page do not provide Content controls for these ContentPlaceHolder controls.
Let us now define a Web Form that uses this master page.
<%@ Page Language="C#" MasterPageFile="~/Site.master" CodeFile="BookHome.aspx.cs" Inherits="BookHome" Title="Book Home" %> <asp:Content ID="Content1" ContentPlaceHolderID="mainContent" Runat="Server"> <h1>Book Rep System Home</h1> <p>Welcome to the book rep system</p> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="sideContent" Runat="Server"> <h2>New Releases</h2> <p>Core C#</p> </asp:Content>
By removing the markup for the common elements and placing them into the master page, you are left with a Web Form that is quite striking in its clarity and conciseness. It contains only the content that is unique to this page. The result, using a style sheet quite similar to that shown in Listing 6.8, is shown in Figure 6.13.
Figure 6.13 Sample Web Form and master page
Notice that all content in this page is contained within either of the two Content controls. Because the Web Form uses a master page, ASP.NET does not allow us to place any markup outside of these two controls. If you do place content outside of a Content control, you will see a Parser Error (see Figure 6.14).
Figure 6.14 Parser error
Nested Master Pages
Master pages can be nested so that one master page contains another master page as its content. This can be particularly useful for Web sites that are part of a larger system of sites. For instance, the master page shown in Figure 6.13 could be just one intranet in a much larger system. You might thus want a way to move between these intranets. Nested master pages provide this mechanism. Figure 6.15 illustrates how the master page in Figure 6.13 can be a child nested inside another parent master page.
Figure 6.15 Nested master pages
To nest a master page within another master page, the child master page simply needs a Content control that maps to a ContentPlaceHolder control in the parent master page, as well as the appropriate MasterPageFile attribute in the Master directive. For instance, you could modify the previous example of a master page so that it is contained within a Content control, and thus becomes a child master page.
<%@ Master MasterPageFile="~/Parent.master" CodeFile="Child.master.cs" Inherits="Child" %> <asp:Content ID="Content1" ContentPlaceHolderID="parentContent" Runat="Server"> <div id="container"> <div id="header"> <asp:Image runat="server" ID="imgLogo" ImageUrl="~/images/cool.gif" /> </div> <div id="sideArea"> <div id="menu"> <asp:BulletedList ID="blstSample" runat="server" DisplayMode="HyperLink"> <asp:ListItem Value="">Home</asp:ListItem> <asp:ListItem Value="">Products</asp:ListItem> <asp:ListItem Value="">About</asp:ListItem> </asp:BulletedList> </div> <div id="sideAreaBox"> <asp:ContentPlaceHolder ID="sideContent" runat="server"> <p>default side content</p> </asp:ContentPlaceHolder> </div> </div> <div id="mainArea"> <asp:ContentPlaceHolder ID="mainContent" runat="server"> <p>default main content</p> </asp:ContentPlaceHolder> </div> <div id="footer"> <p> This site is not real. It is an example site for Core ASP.NET book. </p> </div> </div> </asp:Content>
Your parent master page is quite straightforward with just the one ContentPlaceHolder control. Once again, the formatting and positioning is handled by CSS.
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Parent.master.cs" Inherits="Parent" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title> <link rel="stylesheet" type="text/css" href="~/styles.css" /> <link rel="stylesheet" type="text/css" href="~/parent.css" /> </head> <body> <form id="form1" runat="server"> <div id="topNav"> <p> Pearson Ed Navigator<br /> <asp:DropDownList ID="drpPlaces" runat="server"> <asp:ListItem>Book Rep System</asp:ListItem> <asp:ListItem>Addison-Wesley</asp:ListItem> <asp:ListItem>Prentice Hall</asp:ListItem> </asp:DropDownList> </p> </div> <asp:contentplaceholder id="parentContent" runat="server" /> </form> </body> </html>
How Master Pages Work
When a page that uses a master page (i.e., a content page) is requested, ASP.NET merges the content page and master page together (assuming of course that both have already been compiled). It does so by inserting the master page's content at the beginning of the content page's control tree. This means that the master page content is actually a control that is added to the page. In fact, the master page control is a subclass of the UserControl class (which is covered later in the chapter). Thus, the master page control is the root control in the page's control hierarchy. The content of each individual Content control is then added as a collection of child controls to the corresponding ContentPlaceHolder control in the master page control. This occurs after the PreInit event but before the Init event of the page.
Like any control, master pages have their own sequence of events that are fired as part of the page lifecycle. Because it is the root control in the page's control hierarchy, its events are always fired before the control events in any content pages. As a result, it is important that you do not conceptualize the master page as a "master" in the sense of a "controller" page. That is, the master page should not be orchestrating and controlling what happens in the individual content pages it contains. The master page is simply a template page and should control only those server controls it directly contains. Thus, in general, you should endeavor to keep the master page and the content pages as uncoupled as possible.
Referencing Issues with Master Pages
Because master page content is ultimately inserted into the content page's control tree, there are some potential issues to be aware of with external references inside of master pages. Because the user's request is for the content page and not the master page, all URL references are relative to the content page. This can cause some problems when the master page and the content pages are in different folders within the site.
For instance, let us imagine a situation in which your content page is in a folder under the root named content and your master page is contained in a folder under the root named master; inside this master folder, you also have a subfolder named images. Let's say you want to reference an image named logo.gif, which is inside the images folder of master. In such a case, the following references inside your master page do not work.
<img src="images/logo.gif" /> body { background-image: url(images/logo.gif); } <img src="~/master/images/logo.gif" />
The first two references in fact refer to /content/images/logo.gif, because all relative references are relative to the content page. The second reference doesn't work either because the application relative symbol (~) only works with server controls.
One alternative to this problem is to use an absolute reference to the site root.
<img src="/master/images/logo.gif" />
The problem with this approach is its fragility; that is, the reference breaks if the site structure changes. Another approach is to use a server control, as in the following.
<asp:Image runat="server" id="a" ImageUrl="~/master/images/logo.gif" />
This approach works because server controls within master pages that contain URLs have their URLs modified by the ASP.NET environment.
Programming the Master Page
As you have seen, the combined master and content pages appear to the user as a single page whose URL is that of the requested content page. From a programming perspective, the two pages act as separate containers for their respective controls, with the content page also acting as the container for the master page. Yet, because the master page content becomes merged into the content page, you can also programmatically reference public master page members in the content page.
Why would you want to do this? Perhaps your master page contains a control whose content varies depending upon which content page is being viewed. One common example is a master page that contains an advertisement image; the precise advertisement to display in that control might vary depending upon which part of the site is being viewed. The master page might also contain a secondary navigation area that again differs depending upon which part of the site is being visited.
There are two principal ways of accessing content in the master page within the content page. You can do so via the FindControl method of the Master object or via public members that are exposed by the master page.
Let us begin by examining the FindControl approach. The FindControl method searches the current naming container for a specified server control and returns a typed reference to it. Thus, you can retrieve a TextBox named txtOne from the current Web Form via the following.
TextBox one = (TextBox)this.FindControl("txtOne"); String contents = one.Text;
Notice that the reference returned from the method needs to be cast to the appropriate control type. Of course, it doesn't make too much sense to search the Page naming container for the control when you could replace these two lines with the simpler form with which you are accustomed, namely string contents = txtOne.Text. Where FindControl is truly useful is in those situations where you need to reference a control that is "hidden" within some other naming container, such as a Wizard or GridView control or within a master page. For instance, imagine that you have the following HyperLink control contained within your master page.
<asp:HyperLink ID="imgbtnAd" runat="server" />
Now, let's say that you want to change the image and the destination URL for this control in each of your content pages. You could so with the following code somewhere in your content page's code-behind class.
HyperLink ad = (HyperLink)Master.FindControl("imgbtnAd"); if (ad != null) { ad.ImageUrl = "~/Images/something.gif"; ad.NavigateUrl = "http://www.somewhere.com"; }
Although this approach does work, it is not ideal. A better approach is to safely encapsulate the data you need from the master page into public properties, which you could then access within your content pages. This way, your content pages are not coupled to the implementation details of the master page. The following example adds two properties to the code-behind for the master page. It allows content pages to manipulate the image and navigation URLs of the HyperLink control in the master page.
public partial class ProgrammedContentMaster : System.Web.UI.MasterPage { public string AdImageUrl { get { return imgbtnAd.ImageUrl; } set { imgbtnAd.ImageUrl = value; } } public string AdNavigateUrl { get { return imgbtnAd.NavigateUrl; } set { imgbtnAd.NavigateUrl = value; } } }
Your content pages can now use these properties; to do so requires the use of the Master property of the Page class. Unfortunately, you cannot simply reference one of these properties directly from the Master property in your content page code-behind, as shown here.
Master.AdImageUrl = "~/Images/something.gif";
You cannot do this because the Master property returns an object of type MasterPage, which is the base class for all master pages. Of course, this general MasterPage class knows nothing of the properties you have just defined in your master page. Instead, you must cast the Master property to the class name of your master page, and then manipulate its properties.
ProgrammedContentMaster pcm = (ProgrammedContentMaster)Master; pcm.AdImageUrl = "~/Images/something.gif"; pcm.AdNavigateUrl = "http://www.somewhereelse.com";
An alternative to casting is to add the following MasterType directive to your content pages.
<%@ MasterType VirtualPath="~/ProgrammedContentMaster.master" %>
This changes the Master property of the Page class so that it is strongly typed (that is, it is not of type MasterPage, but of type ProgrammedContentMaster). This eliminates the need for casting the Master property, and thus you can manipulate the custom properties directly.
Master.AdImageUrl = "~/Images/something.gif"; Master.AdNavigateUrl = "http://www.somewhereelse.com";
Master Pages and Themes
ASP.NET themes provide a centralized way to define the appearance of a Web site. Although your content pages can make use of themes, you can simply use master pages to set the theme for your site as a whole. That is, you cannot use the Theme attribute within the Master directive at the top of the master page (although you can still do so in the Page attribute of each of your content pages).
However, you can use your master page to provide a user interface element that allows the user to browse and dynamically set the theme for your content pages. You may recall back in Listing 6.4, you programmatically set the theme of a page within the PreInit event of the page and you used ASP.NET session state to store the currently selected theme. Unfortunately, you cannot set the theme for your content pages within the PreInit event of the master page. Instead, you must have the PreInit event handler within the content page. If you have hundreds or even thousands of content pages, does that mean you must have the same PreInit event handler in all of these content pages?
Fortunately, no; you can make use of some simple object-oriented inheritance so that you only need code the PreInit event handler once. Recall that the code-behind class for all Web Forms has the Page class as its base class. You can define your own class that inherits from this base class and which contains the PreInit event handler that sets the themes. This new class then becomes the base class for the code-behind classes in your site.
The example site contained in Listings 6.9 through 6.13 demonstrates this technique (along with the other material covered in this chapter on master pages). It uses master pages to specify the structure of the site, themes, and CSS to control the appearance of the site's pages. The master page contains both an advertisement banner image that is customized by each content page as well as a theme selector. Figures 6.16 and 6.17 illustrate how the example appears with its two themes.
Figure 6.16 Combining cool theme with master pages
Figure 6.17 Combining professional theme with master pages
Listing 6.9 contains the code for the new class that will become the base class for all your Web Forms. Like Listing 6.4, it simply retrieves the theme selected by the user from the session state and applies it to the (content) page. This class file should be saved in your project's App_Code folder.
Listing 6.9. ParentPage.cs
public class ParentPage: Page { /// <summary> /// Sets the theme of the page based on the current /// session state /// </summary> protected void Page_PreInit(object sender, EventArgs e) { string themeName = (string)Session["themeName"]; if (themeName != null) this.Page.Theme = themeName; else this.Page.Theme = "Cool"; } }
I won't bother showing you all the content pages in the site. Listing 6.10 illustrates one sample content page (the home page).
Listing 6.10. Default.aspx
<%@ Page Language="C#" MasterPageFile="~/BookWithThemes.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" Title="Master with Dynamic Themes - Home" %> <%@ MasterType VirtualPath="~/BookWithThemes.master" %> <asp:Content ID="Content1" ContentPlaceHolderID="sideContent" Runat="Server"> <h2>Featured Book</h2> <h3>Core C# and .NET<br /> <asp:Image ID="imgBook" runat="server" CssClass="sideImage" ImageUrl="~/images/0131472275.gif" AlternateText="Cover image of Core C# book"/></h3> <p>Core C# and .NET is the no-nonsense, example-rich guide to achieving exceptional results with C# 2.0 and .NET 2.0. Writing for experienced programmers, Stephen Perry presents today's best practices for leveraging both C# 2.0 language features and Microsoft's .NET 2.0 infrastructure.</p> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="mainContent" Runat="Server"> <h1>Book Rep System Home</h1> <p> This set of pages demonstrates how master pages can contain a dynamic theme selector. This set of pages demonstrates how master pages can contain a dynamic theme selector. This set of pages demonstrates how master pages can contain a dynamic theme selector. This set of pages demonstrates how master pages can contain a dynamic theme selector. </p> </asp:Content>
The code-behind for this sample content page (see Listing 6.11) must be altered to use your ParentPage class as its base class. Notice as well that it modifies properties exposed by the master page to customize the advertisement that appears within the master page.
Listing 6.11. Default.aspx.cs
public partial class Default : ParentPage { protected void Page_Load(object sender, EventArgs e) { Master.AdImageUrl = "~/Images/ads/ad1.gif"; Master.AdNavigateUrl = "http://www.aw-bc.com/newpearsonchoices"; } }
Listing 6.12 defines the markup for the master page.
Listing 6.12. BookWithThemes.master
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="BookWithThemes.master.cs" Inherits="BookWithThemes" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div id="container"> <div id="header"> <div id="themes"> <p>Theme <br /> <asp:DropDownList ID="drpThemes" runat="server" AutoPostBack="true" OnSelectedIndexChanged= "drpTheme_selectedChanged"> </asp:DropDownList> </p> </div> <div id="bannerAd"> <asp:HyperLink ID="imgbtnAd" runat="server" /> </div> <div class="clearBreak"></div> <div id="logo"> <asp:Image runat="server" ID="imgLogo" SkinID="logo"/> </div> </div> <div id="sideArea"> <div id="masterMenu"> <asp:BulletedList ID="blstSample" runat="server" > <asp:ListItem Value="Default.aspx"> Home</asp:ListItem> <asp:ListItem Value="Products.aspx"> Products</asp:ListItem> <asp:ListItem Value="About.aspx"> About</asp:ListItem> </asp:BulletedList> </div> <div id="sideAreaBox"> <asp:ContentPlaceHolder ID="sideContent" runat="server"> <p>default side content</p> </asp:ContentPlaceHolder> </div> </div> <div id="mainArea"> <asp:ContentPlaceHolder ID="mainContent" runat="server"> <p>default main content</p> </asp:ContentPlaceHolder> </div> <div id="footer"> <p> This site is not real. It is an example site for Core ASP.NET book. </p> </div> </div> </form> </body> </html>
Like the other master pages examined in this chapter, this master page contains no formatting. The CSS and skins of your themes control the appearance of each page. The master page contains four main sections: <div id="header">, <div id="sideArea">, <div id="mainArea">, and <div id="footer">. The sideArea and mainArea sections contain the two ContentPlaceHolder controls. The header section contains the logo image, an advertisement image, and a DropDownList that allows the user to change the theme. The theme list is not filled via markup, but instead is filled programmatically in the code-behind class for this master page, as shown in Listing 6.13.
Listing 6.13. BookWithThemes.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; // Note that you need to include this namespace reference using System.IO; public partial class BookWithThemes : System.Web.UI.MasterPage { /// <summary> /// Populate theme list based on themes in App_Themes folder /// </summary> protected void Page_Load(object sender, EventArgs e) { // Dynamically load the drop-down list only the first time if (!IsPostBack) { // Themes must be in this location string path = Server.MapPath("~/App_Themes"); // Verify this location exists if (Directory.Exists(path)) { // Retrieve array of theme folder names String[] themeFolders = Directory.GetDirectories(path); // Process each element in this array foreach (String folder in themeFolders) { // Retrieve information about this folder name DirectoryInfo info = new DirectoryInfo(folder); // Add this folder name to the drop-down list drpThemes.Items.Add(info.Name); } // Once all the themes are added to the list, you // must make the content page's current theme the // selected item in the list // First search the list items for the page's // theme name ListItem item = drpThemes.Items.FindByText(Page.Theme); // Now set the selected index of the list (i.e., // select that list item) to the index of the list // item you just found. drpThemes.SelectedIndex = drpThemes.Items.IndexOf(item); } } } /// <summary> /// Event handler for the theme selector /// </summary> protected void drpTheme_selectedChanged(object s, EventArgs e) { // Save theme in session string theme = drpThemes.SelectedItem.Text; Session["themeName"] = theme; // Re-request page string page = Request.Path; Server.Transfer(page); } /// <summary> /// Property to get/set the url of the advertisement image /// </summary> public string AdImageUrl { get { return imgbtnAd.ImageUrl; } set { imgbtnAd.ImageUrl = value; } } /// <summary> /// Property to get/set the url for the link surrounding the /// advertisement image. /// </summary> public string AdNavigateUrl { get { return imgbtnAd.NavigateUrl; } set { imgbtnAd.NavigateUrl = value; } } }
The only remaining files are the skins and CSS for the two themes. For space reasons, I do not include them here (although they can be downloaded from my Web site at http://www.randyconnolly.com/core). They are quite similar to those shown in Listings 6.5 through 6.8.