Master Pages in Detail
In Chapter 1 we had a brief look at the idea of master pages, showing how they provide a template for all content pages. This provides a way to create a consistent look for a site, since the look is defined in the master page. Let's refresh ourselves about how this works.Figure 5.1 shows an example of two content pages using a master page. The master page defines the page layoutthat is, the shared UI and code plus any default content. In this case it is the light shaded content at the top and left, representing menus and other navigation features. The master page defines content areas using the ContentPlaceHolder control, and it is into these areas that content pages place their content (shown as dark shaded areas in the figure). Pages that use a master page to define the layout can place content only in the areas defined by the ContentPlace Holder, thus enabling a consistent site design.
Figure 5.1. Master pages in action

Creating Master Pages
In Visual Studio .NET "Whidbey," creating master pages is simply a matter of selecting Master Page from the Add New Item dialog. The newly created master page is just an ASP.NET page with a different file extension (.master), so it fits with your existing knowledge. You don't have to learn any new techniques, apart from the use of the ContentPlaceHolder control. Listing 5.1, for example, shows the contents of a master page newly added to a site.
Listing 5.1 A Simple Master Page
<%@ Master language="VB" %>
<script runat="server">
</script>
<html>
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form runat="server">
<asp:ContentPlaceHolder
id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</form>
</body>
</html>
You can see that this looks similar to existing ASP.NET pages and contains simple HTML and ASP.NET controls. The main difference between this page and a standard ASP.NET page is the use of the Master directive and the file suffix .master. The critical point is the use of the Content PlaceHolder control, which dictates where content pages can insert content. The id attribute uniquely identifies the placeholder, allowing more than one placeholder to be in a master page. The master page can have code as well as content, allowing the master page to be dynamic.Turning this empty master page into one that defines the look and feel of a site is simply a matter of adding controls to get the required look. Figure 5.2, for example, shows the addition of a table to define the page layout, with an area at the top where the logo and site description sit and a region down the left for the menu. In the middle we have the Content PlaceHolder, which is the area we are leaving for content pages to fill in.
Figure 5.2. The master page in design view

Using a Master Page
To create a page that uses the master page, you pick Content Page from the Add New Item dialog, at which point you get the opportunity to pick which master page you wish the content page to inherit from, as shown in Figure 5.3.
Figure 5.3. Picking a master page for a content page

When first created, the content page contains a single line of code:
<%@ Page language="VB" master="~/mysite.master" %>
Figure 5.4 shows this content page in design view. Notice how the content defined in the master is grayed out and disabledthe only area allowed for editing is that defined by the Content control.
Figure 5.4. A content page with an attached master

The confusing thing here is that this Content control doesn't seem to exist in the fileremember there was only a single line, the Page directive. This is because at design time the content of the master page is rendered, but our page defines no content, so an empty region is displayed so the Designer can prompt you where to add the Content control. This can be done either by selecting the Create Empty Content option from the Common Tasks menu or by simply dragging controls from the Toolbox into this region.Listing 5.2 shows the source view for a content page with a couple of controls added.
Listing 5.2 Using a Master Page (MyPage.aspx)
<%@ Page Language="VB" Master="MySite.master" %>
<asp:Content id="Content1" ContentPlaceHolderId="ContentPlaceHolder1"
runat="server">
<asp:Button id="Button1" runat="server" text="Button" />
<asp:ListBox id="ListBox1" runat="server">
</asp:ListBox"
</asp:Content>
The local content is within the Content controlcontent in a page that has a master page cannot be outside a Content control. This ensures that all content pages using a master have a consistent look. Since master pages can contain multiple content areas, the id of the ContentPlaceHolder control is used to link the Content control to the ContentPlaceHolder control in the master page. When the page is constructed, ASP.NET first adds all of the content from the master page. Then it loops through the ContentPlaceHolder controls and, for each, looks in the content page for a Content control where the ContentPlaceHolderId matches the id of the ContentPlaceHolder. This ensures that the correct content is placed in the correct holder.
Default Content
Along with layout and code that applies to all pages, the master page can also supply default content, which can be overridden by content pages or displayed if not overridden. This is achieved by simply inserting the content within the ContentPlaceHolder element. For example, our MySite.master page could have the following default content:
<asp:ContentPlaceHolder
id="ContentPlaceHolder1" runat="server">
<h2>Welcome</h2>
Welcome to my site, where you'll find
lots of interesting stuff.
</asp:ContentPlaceHolder>
Creating a new content file based on this master would give us the following line of code:
<%@ Page Language="VB" master="~/MySite.master" %>
Since we haven't specified a Content control, all content is provided by the master page, as shown in Figure 5.5.
Figure 5.5. A content page with no content other than default content

Nested Master Pages
Master pages aren't limited to a single master and content pages; the architecture allows for nested master pages, where a master page can have a master page. This is particularly useful for sites that require some overall branding and look but that also have subsites whose look must be consistent. For example, consider a corporation with group intranetsperhaps one for the sales department and one for research. The company wishes to have an overall look, including menus between the subsites, but allows the departments to design their parts of the site to fit their business needs. In this situation you could have three master pagesthe top-level master defining the corporate site image, a submaster for the sales department, and a submaster for the research department. The sales and research submaster pages would define the corporate master as their master page. The inheritance rules of master pages mean that any pages using one of the submaster pages receives content from all master pages in the hierarchy (see Figure 5.6).
Figure 5.6. Using nested master pages

Notice that you can inherit from any level of the hierarchyyou aren't limited to using the bottom level. This allows you to provide generic content pages that apply to the whole site, as well as pages that apply to individual site areas. Let's take a look at the code that makes this possible, starting with the site master as shown in Listing 5.3.
Listing 5.3 The Site Master Page (BigCorp.master)
<%@ Master %>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/image/library/english/10191_MySite.css">
</head>
<body>
<form runat="server">
<table width="100%" border="0">
<tr>
<td>
<asp:Hyperlink ImageUrl="home.gif" runat="server"
NavigateUrl="BigCorp_Default.aspx" />
</td>
<td>
<h1>Big Corp Intranet</h1>
</td>
<td>
<a href=">Sales</a>
</td>
<td>
<a href=">Research</a>
</td>
</tr>
</table>
<asp:ContentPlaceHolder runat="server"
id="MainContentRegion">
Welcome to Big Corp. Please use the menus above
to select the required department.
</asp:ContentPlaceHolder>
</form>
</body>
</html>
This simple master page, containing some content and a placeholder, is shown in design view in Figure 5.7.
Figure 5.7. The site-wide master page (BigCorp.master)

Now consider Listing 5.4, which shows a submaster page that inherits from the first master page.
Listing 5.4 A Submaster Page (BigCorp_Sales.master)
<%@ Master Master="BigCorp.master"%>
<asp:Content ContentPlaceHolderId="MainContentRegion"
runat="server">
<table border="0" width="100%">
<tr>
<td>
<h2>Big Corp Sales</h2>
</td>
</tr>
<tr>
<td>
<table border="0" width="100%">
<tr>
<td><a href=" Menu 1</a></td>
<td><a href=" Menu 2</a></td>
<td><a href=" Menu 3</a></td>
<td><a href=" Menu 4</a></td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<asp:ContentPlaceHolder runat="server"
id="SalesContentRegion" />
</td>
</tr>
</table>
</asp:Content>
Because this page inherits from a master page, all content must be within a Content control, with a ContentPlaceHolderId matching that of the master ContentPlaceHolder. However, we can also include Content PlaceHolder controls in this master, allowing content pages to add content to our content. The design view for BigCorp_Sales.master is shown in Figure 5.8, where you can see that Content1 is the content area defined by BigCorp.master, and Content2 is the region defined for content pages to use.
Figure 5.8. The nested sales master page (BigCorp_Sales.master)

Using the nested master page is the same as creating any other content page. For example, Listing 5.5 shows a content page using BigCorp _Sales.master.
Listing 5.5 A Content Page Using a Nested Master Page
<%@ Page Master="BigCorp_Sales.master" %>
<script runat="server">
Sub Page_Load(sender As Object, e As EventArgs)
End Sub
</script>
<asp:Content ContentPlaceHolderId="SalesContentRegion"
runat="server">
Welcome to the Big Corp Sales Intranet
</asp:Content>
Here the ContentPlaceHolderId matches the immediate parent, and since the parent inherits from another page, the ultimate result is a combination of both master pages and the child ASP.NET content page. So, if we have two child content pages, one for the sales division and one for the research division, we'll end up with a site as shown in Figure 5.9.
Figure 5.9. Using nested master pages

In Figure 5.9 you can see that although both departments have chosen a different style of menu (one vertical and one horizontal), the top of the page remains constant because it is defined in the top-level master.
Master Page Configuration
Attaching a master page directly to a page provides great flexibility but does have a downside. Not only must developers know the name of the master but they are also free to not use it, which could result in pages not fitting with the overall site design. To ensure that a master page cannot be omitted, master pages can be attached globally by modifying the Web configuration file, as shown in the following fragment:
<configuration>
<system.web>
<pages master="BigCorp.master" />
</system.web>
</configuration>
A master page attached locally via the Master attribute, however, overrides any global master pages defined in web.config.
Device-Specific Master Pages
ASP.NET has a new architecture for detecting and rendering content to mobile devices, and this control architecture has also been implemented by the master page processing, enabling different master pages to be used for different devices. For example, it would be possible to supply different master pages for Internet Explorer and Mozilla. This is achieved by creating separate master pages and then in the page prefixing the master attribute with the name of the device, as shown below:
<%@ Page master="default.master"
Mozilla:master="mozilla.master" %>
When this page is accessed by a Mozilla browser, mozilla.master is used. All other browsers use the default master page. The results can be seen in Figure 5.10, where the content simply differs for each browser. Where this comes into its own is in supporting multiple devices, such as small-screen devices, where your master page might need to be very different, perhaps to incorporate a different menu structure.
Figure 5.10. Device-specific master pages

Mobile device support is covered in more detail in Chapter 10.
Like the rest of the device-specific features, the list of devices can be found in the CONFIG directory under the .NET Framework installation directory. These are device capability files, detailing the exact features of each browser. |
Event Ordering
Because events can be present in both the master and content pages, the event order follows that of User Controls. So, for events that are captured twice, such as the Page_Load event, the content page event is fired first.
Accessing the Master Page
Content pages that have a master have a property, Master, allowing access to the master page. The Master property returns an instance of Page (from System.Web.UI), and thus you can access all of the properties and methods in the same way as for other pages. For example, to access a control from the master page you can do one of two things. The first option is to expose the control through a public property on the master page (Listing 5.6) and access that property from the content page (Listing 5.7).
Listing 5.6 Exposing Master Page Properties (MySite.master)
<%@ Master %>
<script runat="server">
Public ReadOnly Property Home() As Hyperlink
Get
Return homeUrl
End Get
End Property
</script>
<form runat="server">
<asp:Hyperlink id="homeUrl"
NavigateUrl="default.aspx" />
</form>
Listing 5.7 Accessing Exposed Master Page Properties (MyPage.aspx)
<%@ Page Master="MySite.master" %>
<script runat="server">
Sub Page_Load(sender As Object, e As EventArgs)
Dim Url As String = Master.Home.NavigateUrl
End Sub
</script>
Listing 5.6 shows a master page with a control exposed as a Public Property, and Listing 5.7 shows a content page accessing that control through the exposed property.The second approach is to access the controls late bound and use the FindControl method to find the controls, as shown in Listing 5.8.
Listing 5.8 Accessing Master Page Contents Late Bound
<%@ Page Master="MySite.master" %>
<script runat="server">
Sub Page_Load(sender As Object, e As EventArgs)
Dim Url As String = _
CType(Master.FindControl("homeUrl"), _
Hyperlink).NavigateUrl
End Sub
</script>
While the first solution does require you to expose controls as properties, this is required only for controls that are needed external to the master page, and this approach does provide a more efficient solution than the late-bound approach.
• Table of ContentsA First Look at ASP.NET v. 2.0By
Publisher: Addison WesleyPub Date: October 23, 2003ISBN: 0-321-22896-0Pages: 528
"This book provides a first look at the new major release of ASP.NET. The authors have worked closely with the ASP.NET team at Microsoft to make sure that this book is authoritative, accurate, and informative. Anyone using ASP.NET will find a wealth of useful info on the next version."
-Scott Guthrie, Product Unit Manager, Web Platforms and Tools Team, Microsoft Corporation
A First Look at ASP.NET v. 2.0 systematically prepares you for Microsoft''''s ASP.NET 2.0 Web development platform, showing how to use it to reduce development time and costs, improve the performance of Web applications and services, simplify deployment and management, and extend your applications to mobile clients.
Drawing on extraordinary insider access to Microsoft''''s ASP.NET development team, three renowned ASP.NET experts cover every key platform enhancement, from Master Page templates for standardizing look and feel to improved security and data- access controls. They go far beyond already published white papers and previews, presenting detailed development techniques, best practices, and sample code that will give you a running start with ASP.NET 2.0.
This book''''s detailed coverage includes:
Streamlining database integration with "code-free" data binding and ASP.NET 2.0''''s new data source controls
Using Master Pages to improve your control over application look and feel
Strengthening security with membership providers, security server controls, cookieless forms authentication, and the new Role Manager
Simplifying personalization with ASP.NET 2.0 ThemesBuilding fast, flexible portals with Web Parts and the new Portal Framework
Delivering more effective mobile device support-with less complexity
Previewing new ASP.NET 2.0 controls and changes in existing controls
Using Microsoft''''s powerful new .NET and built-in administration tools
Whether you''''re already developing with ASP.NET, or preparing to migrate from ASP, A First Look at ASP.NET v. 2.0 gives you complete information for assessing ASP.NET 2.0-and making the most of it.