Skip navigation

Standardize Your Site Fast With Master Pages

ASP.NET 2.0 includes a flexible page-template system with excellent visual-designer support.

asp:feature

LANGUAGES: VB .NET

ASP.NET VERSIONS: 2.0

 

Standardize Your Site Fast With Master Pages

ASP.NET 2.0 includes a flexible page-template system with excellent visual-designer support.

 

By Paul Wilson

 

Most Web sites have a layout shared across all pages, but neither classic ASP nor ASP.NET has ever included automatic support for page templates. And although include files typically were used in ASP classic, and user controls and base Page classes are often used in ASP.NET, these techniques were not built in, and there was no designer support. ASP.NET 2.0 changes this by including a flexible page-template system called Master Pages. It should be easy enough for designers to use, while powerful enough for developers.

 

The easiest way to learn this new master-pages technique is to look at examples, so the rest of this article will walk you through several examples, starting with the simplest scenario and leading up to the more advanced.

 

This first example illustrates the new concepts and syntax of Master Pages by creating a master with a site header, left and right sidebars, a site footer, and a single content "region." First, create a Master Page for the common layout. The Master Page is very similar to a user control, except that it has the new file extension of master and also has a Master directive. Unlike most user controls, the Master Page will contain the top-level HTML tags, such as , , , and

, that usually are in each separate page. Simply create the common layout using the normal HTML tags and server controls, which, in this case, consist of a table that defines the header and footer, as well as another embedded table to define the left and right sidebars (see Figure 1). The content region that will be replaced in the actual pages is then marked by the new ContentPlaceHolder control, where the ID that is assigned to this control will be matched in the actual page. Any content included inside the ContentPlaceHolder control becomes default content that will be rendered only if the actual page does not have a matching content region that overrides this one.

 

<%@ master language="VB" %>

  Master Pages

  

      href="StyleSheet.css" />

  

  

Site Header Goes Here

  

  

    

    

    

  

  

      Site Left SideBar Goes Here

      

Master Pages

      

        This is Default Content -- Override on Page

      

      Site Right SideBar Goes Here

Site Footer Goes Here

Figure 1. This IntroLayout.master file is the Master Page that defines the common layout for other pages. It includes a header, left and right sidebars, a footer, and a single content region.

 

Finally, create a content page for the page-specific content, where the new Master attribute is used in the Page directive to link the Master Page. Other than an optional server-script block, the only top-level elements allowed are the new Content controls that replace the matching ContentPlaceHolder controls that were defined in the Master Page (see Figure 2). The Content controls have a ContentPlaceHolderID attribute that must match the ID that was assigned to the ContentPlaceHolder control it is overriding. Otherwise, the page-specific content inside the content region consists of the usual HTML tags and server controls, including page or control event handlers. Note that a default master can be specified in the web.config file by including a element with a Master attribute, although this is not currently supported in the designer.

 

<%@ page language="VB" master="~/IntroLayout.master" %>

    contentplaceholderid="Main">

  

Introduction to Master Pages

  This is Page Content Overridden from Master

  

  

      onclick="Submit_Click" />

  Result:

Figure 2. This IntroContent.aspx file is the content page that uses the IntroLayout.master Master Page. It includes only the page-specific content for the region defined in that Master Page.

 

This example certainly can be written entirely in Notepad using just the SDK, but Master Pages really shine when using an IDE like the "Whidbey" version of Visual Studio .NET. The design-time view of the content page using this Master Page, shown in Figure 3, shows how the entire page is rendered visually at design time. The Master Page itself is displayed, but is dimmed because it is not editable itself, while the content page is fully designable, with the new design task panel surrounding it. Unlike all the page-template methods that have been used in the previous versions of VS .NET, there is no loss of IntelliSense, drag-and-drop, or any other design features.

 


Figure 3. The Whidbey version of Visual Studio .NET includes design-time support of Master Pages. The Master Page itself is displayed dimmed, while the page-specific content is editable.

 

Multiple Regions and Header Tags

This next example illustrates the use of multiple content regions in Master Pages and demonstrates how to extend master pages with custom public properties. First, change the right sidebar to be a ContentPlaceHolder control, with ID Right in this case, so that this region also will be replaceable by a Content control in each page that links to this master (see Figure 4). This new region will display in the VS .NET designer and be fully editable, just like the other content region, and its default content will be rendered if it is not overridden in the actual page. Next, change the tag to be part of a ContentPlaceHolder control, so that now the title, style-sheet link, and metatags can easily be set in each actual page. Note that this content region will not be displayed in the designer because it is in the head instead of the body, but it will be easily editable in the HTML source, just like normal head tags. Next, create a public string property (or field in this case, for simplicity) named LeftSideBar and create a Literal control for the left sidebar that has its Text property set to the value of this property in the PreRender event of the master. Another content region also could have been created in this simple example, but it is important to understand that custom public properties in Master Pages are easy to create and use for the more-complex cases that may be encountered.</p> <p>   </p> <p><%@ master language="VB" %></p> <p><script runat="server" language="vb"> function advagg_mod_2() { // Count how many times this function is called. advagg_mod_2.count = ++advagg_mod_2.count || 1; try { if (advagg_mod_2.count <= 40) { </p> <p>  Public LeftSideBar As String _</p> <p>      = "Master.LeftSideBar Goes Here"</p> <p>  </p> <p>  Sub Page_PreRender(ByVal sender As Object, _</p> <p>      ByVal e As System.EventArgs)</p> <p>    Left.Text = LeftSideBar</p> <p>  End Sub</p> <p> // Set this to 100 so that this function only runs once. advagg_mod_2.count = 100; } } catch(e) { if (advagg_mod_2.count >= 40) { // Throw the exception if this still fails after running 40 times. throw e; } else { // Try again in 250 ms. window.setTimeout(advagg_mod_2, 250); } } } function advagg_mod_2_check() { if (window.jQuery && window.Drupal && window.Drupal.settings) { advagg_mod_2(); } else { window.setTimeout(advagg_mod_2_check, 250); } } advagg_mod_2_check();</script></p> <p><html></p> <p><head></p> <p>  <asp:contentplaceholder id="Head" runat="server"></p> <p>    <title>Master Pages

  

  

      href="StyleSheet.css" />

  

  

Site Header Goes Here

  

  

    

    

    

  

  

      

        Master.LeftSideBar Goes Here

      

      

Master Pages

      

        This is Default Content -- Override on Page

      

      

        Site Right SideBar Goes Here

      

Site Footer Goes Here

Figure 4. This MultipleRegions.master file has multiple regions, including one for the title and other head tags. It also defines a custom public property that easily can be set in each actual page.

 

Finally, change the content page to override the new regions using appropriately matched Content controls, or leave them out if you want to keep the default content defined for each region. Remember that the region used for the HTML head content, including title, style-sheet link, and metatags, must be edited manually in the HTML source because only the body regions are shown in the designer (see Figure 5). Finally, set the value of the custom public property of the Master Page in the Load event, which will even be available in IntelliSense, although you may need to save or reload the master first.

 

<%@ page language="VB" master="~/MultipleRegions.master" %>

    contentplaceholderid="Head">

  Master Pages: Multiple and Head Regions

    contentplaceholderid="Main">

  

Multiple and Head Regions

  This is Page Content Overridden from Master

  

  

    onclick="Submit_Click" />

  Result:

    contentplaceholderid="Right">

  Page-Specific Right SideBar

Figure 5. This MultipleRegions.aspx file is the content page that uses the MultipleRegions.master Master Page. It includes multiple regions, including a region in the HTML head, and uses a custom property.

 

Nested and Dynamic Masters

This last example illustrates the use of nested Master Pages and also demonstrates how to enable dynamic Master Pages that are determined at run time based on user input. Note that nested masters are not supported in the designer, at least for this alpha build, and the method that is required for dynamic masters in this alpha build is not recommended officially because there should be a better, officially supported technique in later builds. First, create a parent master with only a site header, a site footer, and a single child content region, along with an HTML head region as before.

 

Next, create a child master that replaces the child region with a left sidebar exposed as a custom property, a right sidebar exposed as a content region, and the central main content region. The HTML head region must be overridden, also, and replaced with another content region in order for it to be exposed to the actual page, at least in the current alpha build (see the accompanying code download).

Finally, change the content page to link to this child master and override the content regions as before. Next, add a "device filter" master to the page directive, which, in this case, will be named "alternate." Then, override the TestDeviceFilter method and return True when the condition for this alternate master is satisfied (see Figure 6). In this case, the alternate master is used when there is a post-back, although the Form collection had to be used to determine this because IsPostBack is not available this early in the page life cycle. Finally, set the value of the custom public property of the Master Page in the Load event, although this will require type-casting of the master because the master is now dynamic. Again, note that this technique is not officially recommended, but this is the only way to have dynamic masters in the alpha build, which is under discussion and is likely to change to better allow dynamic masters before the final release.

 

<%@ page language="VB" master="~/ChildLayout.master"

    alternate:master="~/MultipleRegions.master" %>

    contentplaceholderid="Head">

  Master Pages: Nested and Dynamic Masters

    contentplaceholderid="Main">

  

Nested and Dynamic Masters

  This is Page Content Overridden from Master

  

  

      onclick="Submit_Click" />

  Result:

    contentplaceholderid="Right">

  Page-Specific Right SideBar

Figure 6. This NestedLayouts.aspx file is the content page that uses the nested ChildLayout.master Master Page. It also dynamically uses the MultipleRegions.master when the page is a post-back.

 

Benefits of Master Pages

The master-pages system is easy for designers to use because it is based on the familiar user-control model of ASP.NET. With nearly complete visualization finally added, though, no code needs to be written. On the other hand, Master Pages are powerful because they support multiple regions, default content, nested templates, and device filters for browser dependence. Master Pages are also fully compiled to have optimal performance, as well as providing a strongly typed programming model that includes design-time IntelliSense of master properties, although there may be some tradeoffs made before the final release to better support dynamic masters.

 

Of course, a production version of ASP.NET 2.0 has not been released yet. However, there are some versions of Master Pages that work with versions 1.0 and 1.1, although they certainly do not have the built-in integration with Visual Studio's designer. See http://www.aspalliance.com/PaulWilson/Articles/?id=13 for an article about Microsoft's original sample and http://www.aspalliance.com/PaulWilson/Articles/?id=14 for a custom version that at least doesn't break the existing designer. The available code download for this article also contains examples nearly identical to the ones in this article that use my custom version of Master Pages in versions 1.0 and 1.1.

 

The sample code in this article is available for download.

 

Paul Wilson is a software architect in Atlanta who recently joined the development team at PRG-Schultz. His WilsonWebForm control allows multiple forms and non-post-back forms in ASP.NET. He is a Microsoft Most Valuable Professional in ASP.NET, a moderator of Microsoft's ASP.NET Forums, a Microsoft Certified Solution Developer, a Microsoft Certified Application Developer, a Microsoft Certified Database Administrator, and a Microsoft Certified Systems Engineer. Visit his Web site, http://www.WilsonDotNet.com, or e-mail him at mailto:[email protected].

 

 

Paul Wilson walks you through how Master Pages will make standardizing your site a snap.

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish