Master Pages in ASP.NET 2.0...

One of the newest features of .NET Framework version 2 web development is the introduction of master pages. Master pages are an alternative to the current method of site templating.


By: Brian Mains Date: July 31, 2004 Download the code.

One of the newest features of .NET Framework version 2 web development is the introduction of master pages. Master pages are an alternative way to the current method of site templating. The nice feature about master pages is that the master page can be edited visually in the Visual Studio .NET editor, instead of creating the HTML manually in the previous alternative.

Before we move onto the future, it is important to understand the concept of Page Templating in ASP.NET 1.1. This approach is to create a custom class that inherits from System.Web.UI.Page. By doing this, the Render or OnInit methods can be overridden to render the HTML for a common template. Each ASP.NET page then inherits from this class. Some more information about creating these classes, or using preexisting classes is available here:

The drawback to this approach is that the HTML content must be added to the class manually, by creating a string of HTML markup to render to the browser. In addition, to create multiple templates to the same site, HTML markup must be rendered independently of each other. There are ways around this; if a base class implements a common set of methods to render common pieces of HTML, the total amount of work needed to create multiple site templates is reduced.

Master pages, containing a *.master file extension, contain the HTML markup for the site template, which can be edited visually in the Visual Studio .NET editor. Each ASP.NET page that will inherit from this master page declares a MasterPageFile property at the @Page directive level. To add content to an ASP.NET page ( also known as the content page) inheriting the master file, the Master Page must declare an <asp:ContentPlaceHolder> element. All content for the content pages will be placed in this block. Any number of placeholders can be defined for a master page, which any number can have content added to it in the content page. In the content page, the <asp:Content> element is used, as shown below:

<asp:Content ID="Content2" ContentPlaceHolderID="plcContent" Runat="server"></asp:Content>

An entire web site can utilize a master page by setting the default master page in the configuration file. A new element called pages allows the declaration of the master page in the master attribute, which can be overridden at the page level.

<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<system.web>
  <pages masterPageFile="BasicTemplate.master"></pages>
</system.web>
</configuration>

Master pages can also inherit from other master pages. This minimizes the amount of work needed to create variations to a common template. One feature this can be useful for is creating a slightly different template for an administrative or help site, where you want the look and feel to be different than the rest of the application. In addition, the content page can override properties defined at the master page level. This is done through the use of a public property defined in the master page. All of this will be illustrated below.

Let's look at the master page. Below is the BasicTemplate.master file that will be used for the example. This master page contains the site template featuring a consistent layout, images, and ad rotator controls that make up the site’s look and feel. The HTML and server controls are still defined the same way in an ASP.NET web page, with a few changes in regards to the new 2.0 syntax. In addition, HTML elements that weren't supported at the server level in version 1.1 are now supported in the beta. The head and body elements can be declared with the runat="server" attribute, and the contents can be accessible at runtime.

The page title and modification date are dynamic attributes defined at runtime within the content page. The content page accesses them through two public property declarations, which then get written out to the browser through the <%= %> notation.

<%@ Master Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">
  'These variables are used to allow the content page
  'to access these properties and make them dynamic
  Private _ModificationDate As String = String.Empty
  Public Property ModificationDate() As String
    Get
      return _ModificationDate
    End Get
    Set(ByVal value As String)
      _ModificationDate = value
    End Set
  End Property

  Private _PageTitle As String = String.Empty
  Public Property PageTitle() As String
    Get
      Return _PageTitle
    End Get
    Set(ByVal value As String)
      _PageTitle = value
    End Set
  End Property
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Heading" runat="server">
  <title><%=PageTitle.Trim()%></title>
  <link rel="stylesheet" type="text/css" href="styles.css" runat="server" />
</head>
<body leftmargin="0" topmargin="0" bottommargin="0" rightmargin="0" marginwidth="0" marginheight="0">
  <form id="frmMain" runat="server">
    <table cellpadding="0" cellspacing="0" border="0" width="100%" align="center">
      <tr>
        <td class="Header" width="200">
          <img alt="Logo" border="0" />
        </td>
        <td class="Header">
          <asp:AdRotator ID="adVertisements" Runat="server" CountClicks="True" />
        </td>
        <td class="Header" align="right">
        </td>
      </tr>
      <tr>
        <td class="Header" style="padding-right: 5px; padding-left: 5px; padding-bottom: 5px; padding-top: 5px" valign="top">
          <br />
          <asp:LinkButton ID="LinkButton1" Runat="server" CssClass="Header">Link 1</asp:LinkButton>
          <br />
          <asp:LinkButton ID="LinkButton2" Runat="server" CssClass="Header">Link 2</asp:LinkButton>
          <br />
          <asp:LinkButton ID="LinkButton3" Runat="server" CssClass="Header">Link 3</asp:LinkButton>
        </td>
        <td valign="top">
          <asp:contentplaceholder id="plcContent" runat="server"></asp:contentplaceholder>
        </td>
        <td valign="top" align="center" width="20%">
        </td>
      </tr>
      <tr>
        <td class="Header" colspan="3" align="center">
          <%=ModificationDate.Trim()%>
        </td>
      </tr>
    </table>
  </form>
</body>
</html>

The content page that inherits from the master page declares an <asp:Content> element to add content to the master page template, with the ContentPlaceHolderID property identifying the ContentPlaceHolder element (defined in the master page) to write the content to. In addition, the code in the page load method overrides the master page to add the page title and the last modified date. To get the modification date, the FileInfo object accesses the current content page and retrieves the last write time of the web page.

<%@ Page Language="VB" MasterPageFile="~/BasicTemplate.master" Title="Home Page" %>

<script runat="server">
  Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
    Try
      Dim objInfo As New System.IO.FileInfo(Server.MapPath(Request.ServerVariables.Get("SCRIPT_NAME")))
      With CType(Me.Master, BasicTemplate_master)
        .PageTitle = "Default Home Page"
        .ModificationDate = objInfo.LastWriteTime.ToShortDateString()
      End With

    Catch ex As Exception
      Response.Write(ex.ToString())
    End Try
  End Sub
</script>

<asp:Content ID="Content2" ContentPlaceHolderID="plcContent" Runat="server"> 
  <table id="tblDefault" cellspacing="0" cellpadding="0" width="90%" align="center">
    <tr>
      <td align="center">
        <h1 class="Title">Home Page</h1>
      </td>
    </tr>
    <tr>
      <td>This is my home page for the master page.
      </td>
    </tr>
  </table>
</asp:Content>

When the page is loaded in the browser, it will appear with the common look-and-feel designed in the .NET editor. This is a simplistic overview of how master pages work. This is a very exciting edition to the .NET framework version 2, and hopefully will be supported thoroughly by the Visual Studio .NET editor. Coming soon are additional articles showing the 2.0 release.

About the Code

The code attached is a project developed with Visual Web Developer. Visual Web Developer is a free tool available from Microsoft on http://www.asp.net. It is a huge download, but is also available in CD or DVD format. As with Beta software, any of the above code can change by the time the final release is made public. Be aware of that.

This example will be used in the future, as I will be creating one common web site example to use for all of the .NET framework version 2 examples provided. I apologize for the lack of images in the examples provided. In future examples, I will be working to add those to the layout, but unfortunately, I didn’t have enough time.

You may download the code here.