4.1. Sharing a Page Header on Multiple Pages

Problem

You have a header that is common to all pages in a site and do not want to repeat the code on every page.

Solution

Create a user control containing the header code and then add the control to each page.

To create the user control:

  1. Create a file with a .ascx extension.

  2. Place the @ Control directive at the top of the file.

  3. Add the HTML you wish to reuse for the header, making sure to avoid using any <html>, <head>, <body>, or <form> elements.

In the code-behind class for the control, use the .NET language of your choice to:

  1. Create a user control code-behind class that inherits from the UserControl class.

  2. (Optional) Establish properties for the control that will provide the ability to programmatically control the basic look of the header.

To use the user control in an ASP.NET page:

  1. Register the control by using the @ Register directive at the top of the page.

  2. Place the tag for the user control where you want the control to be rendered.

To demonstrate this solution, we’ve created a user control that houses some typical header HTML, including <img> tags for a header image and a divider image. We then show how to use the user control in three different ways: with default parameters, with parameters set in the .aspx file, and with parameters set in the code-behind.

The output of a test page that uses the user control is shown in Figure 4-1. (The second divider line appears in green and the third divider line appears in blue when rendered on the screen.) Example 4-1 shows the .ascx file for the user control. Example 4-2 and Example 4-3 show the VB and C# code-behind files for the user control. Example 4-4 shows the .aspx file that uses the user control in the three different ways previously mentioned. Example 4-5 and Example 4-6 show the VB and C# code-behind files for the test page that uses the user control.

Page header user control output

Figure 4-1. Page header user control output

Discussion

User controls provide an easy way to partition pages and reuse the page sections throughout your application. They are very similar to web forms in that they consist of two files: a .ascx file (the user interface) and a code-behind file (.vb or .cs). Since they constitute page sections, the user interface elements they contain generally do not include <html>, <head>, <body>, or <form> elements. Further, you must place the @ Control directive at the top of the .ascx file instead of the @ Page directive used for web forms. The code-behind class for a user control is very similar to the code-behind class for a web form, with the most noticeable difference being that the user control code-behind class inherits from the UserControl class instead of the Page class.

The example we’ve provided to demonstrate this solution shows you how to create a user control to be used as a page header. The user control has three custom properties that provide the ability to programmatically control the basic look of the header.

The HTML for the user control (see Example 4-1) contains a table with two rows and a single column. The first row of the table contains a “logo” style image. The src attribute of the image tag is set to the name of the image that will be used for the default image.

The cell in the second row of the table contains a single-pixel transparent image. This is a classic HTML trick to allow manipulation of a table cell to provide dividers with alterable colors and heights as well as to stretch to the size of the cell. The bgcolor and height attributes of the cell are set to the values that will be the defaults for the color and height of the divider line.

The code-behind contains three properties:

headerImage

Provides the ability to set/get the image that will be displayed in the header

dividerColor

Provides the ability to set/get the divider color

dividerHeight

Provides the ability to set/get the divider height

To use a user control in an ASP.NET page, the control must be registered using the @ Register directive at the top of the page. The TagPrefix and TagName attributes are used to uniquely define the “custom tag” on the ASP.NET page. The TagPrefix is typically set to the namespace of the project. The TagName should be set to a value that describes what the control is used for. The Src attribute is set to the name of the .ascx file of the user control. Here is how we set these attributes in our example:

<%@ Register TagPrefix="ASPCookbook" TagName="PageHeader" 
             Src="CH04UserControlHeaderVB.ascx" %>

Additionally, a tag is placed in the HTML where you want the user control rendered. The tag must be given an id and the runat attribute must be set to "server" or else the user control will not be rendered. Here is the syntax we’ve used for inserting our example user control using the default values:

<ASPCookbook:PageHeader id="pageHeader1" runat="server" />

If you want to change the properties for a user control, you can set them as attributes in the tag. For instance, here is how we set the header image, the divider color, and the divider height in our example:

<ASPCookbook:PageHeader id="pageHeader2" runat="server"
               headerImage="images/oreilly_header.gif" 
               dividerColor="#008000" 
               dividerHeight=12 />

The properties for a user control included in an ASP.NET page can be set in the code-behind in the same manner as setting the attributes for any other HTML or ASP server control. You must declare the control in the class, and then you can set the appropriate values in Page_Load or another method. Here’s how we do it in our example:

Protected pageHeader3 As ASPNetCookbook.VBExamples.UserControlHeaderVB

  ...

pageHeader3.headerImage = "images/ddig_logo.gif"
pageHeader3.dividerHeight = "18"
pageHeader3.dividerColor = ColorTranslator.ToHtml(Color.DarkBlue)

Example 4-1. Page header user control (.ascx)

<%@ Control Language="vb" AutoEventWireup="false" 
            Codebehind="CH04UserControlHeaderVB.ascx.vb" 
            Inherits="ASPNetCookbook.VBExamples.CH04UserControlHeaderVB" %>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
  <tr>
    <td align="center">
      <img id="imgHeader" runat="server" 
           src="images/ASPNetCookbookHeading_blue.gif">
    </td>
  </tr>
  <tr>
    <td id="tdDivider" runat="server" bgcolor="#6B0808" height="6">
      <img src="images/spacer.gif"></td>
  </tr>
</table>

Example 4-2. Page header user control code-behind (.vb)

Option Explicit On 
Option Strict On
'-----------------------------------------------------------------------------
'
'   Module Name: CH04UserControlHeaderVB.ascx.vb
'
'   Description: This module provides the code behind for 
'                CH04UserControlHeaderVB.ascx
'
'*****************************************************************************

Namespace ASPNetCookbook.VBExamples
  Public MustInherit Class CH04UserControlHeaderVB
    Inherits System.Web.UI.UserControl

    'controls on user control
    Protected imgHeader As System.Web.UI.HtmlControls.HtmlImage
    Protected tdDivider As System.Web.UI.HtmlControls.HtmlTableCell

    '*************************************************************************
    '
    '   ROUTINE: headerImage
    '
    '   DESCRIPTION: This property provides the ability get/set the image
    '                used in the header user control
    '-------------------------------------------------------------------------
    Public Property headerImage( ) As String
                        Get
                          Return (imgHeader.Src)
                        End Get
                        Set(ByVal Value As String)
                          imgHeader.Src = Value
                        End Set
                      End Property  'headerImage

    '*************************************************************************
    '
    '   ROUTINE: dividerColor
    '
    '   DESCRIPTION: This property provides the ability get/set the divider
    '                color used at the bottom of the user control
    '-------------------------------------------------------------------------
    Public Property dividerColor( ) As String
                        Get
                          Return (tdDivider.BgColor)
                        End Get
                        Set(ByVal Value As String)
                          tdDivider.BgColor = Value
                        End Set
                      End Property  'dividerColor

    '*************************************************************************
    '
    '   ROUTINE: dividerHeight
    '
    '   DESCRIPTION: This property provides the ability get/set the divider
    '                height used at the bottom of the user control
    '-------------------------------------------------------------------------
    Public Property dividerHeight( ) As String
                        Get
                          Return (tdDivider.Height)
                        End Get
                        Set(ByVal Value As String)
                          tdDivider.Height = Value
                        End Set
                      End Property  'dividerHeight

    '*************************************************************************
    '
    '   ROUTINE: Page_Load
    '
    '   DESCRIPTION: This routine provides the event handler for the page load
    '                event.  It is responsible for initializing the controls 
    '                on the user control.
    '-------------------------------------------------------------------------
    Private Sub Page_Load(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs) _
            Handles MyBase.Load
      'place user code here
    End Sub  'Page_Load
  End Class  'CH04UserControlHeaderVB
End Namespace

Example 4-3. Page header user control code-behind (.cs)

//----------------------------------------------------------------------------
//
//   Module Name: CH04UserControlHeaderCS.ascx.cs
//
//   Description: This module provides the code behind for
//                CH04UserControlHeaderCS.ascx
//
//****************************************************************************
using System;
using System.Web.UI.HtmlControls;

namespace ASPNetCookbook.CSExamples
{
  public class CH04UserControlHeaderCS : System.Web.UI.UserControl
  {
    // controls on the user control
    protected System.Web.UI.HtmlControls.HtmlImage imgHeader;
    protected System.Web.UI.HtmlControls.HtmlTableCell tdDivider;

    //************************************************************************
    //
    //   ROUTINE: headerImage
    //
    //   DESCRIPTION: This property provides the ability get/set the image
    //                used in the header user control
    //------------------------------------------------------------------------
    public String headerImage
                      {
                        get
                        {
                          return(imgHeader.Src); 
                        }
                        set
                        {
                          imgHeader.Src = value;
                        }
                      }  // headerImage

    //************************************************************************
    //
    //   ROUTINE: dividerColor
    //
    //   DESCRIPTION: This property provides the ability get/set the divider
    //                color used at the bottom of the user control
    //------------------------------------------------------------------------
    public String dividerColor
                      {
                        get
                        {
                          return(tdDivider.BgColor);
                        }
                        set
                        {
                          tdDivider.BgColor = value;
                        }
                      }  // dividerColor

    //************************************************************************
    //
    //   ROUTINE: dividerHeight
    //
    //   DESCRIPTION: This property provides the ability get/set the divider
    //                height used at the bottom of the user control
    //------------------------------------------------------------------------
    public String dividerHeight
                      {
                        get
                        {
                          return(tdDivider.Height);
                        }
                        set
                        {
                          tdDivider.Height = value;
                        }
                      }  // dividerHeight

    //************************************************************************
    //
    //   ROUTINE: Page_Load
    //
    //   DESCRIPTION: This routine provides the event handler for the page 
    //                load event.  It is responsible for initializing the 
    //                controls on the user control.
    //------------------------------------------------------------------------
    private void Page_Load(object sender, System.EventArgs e)
    {
      // Put user code to initialize the page here
    }  // Page_Load
  }  // CH04UserControlHeaderCS
}

Example 4-4. Using the page header user control (.aspx)

<%@ Page Language="vb" AutoEventWireup="false" 
         Codebehind="CH04DisplayHeaderVB.aspx.vb" 
         Inherits="ASPNetCookbook.VBExamples.CH04DisplayHeaderVB" %>
<%@ Register TagPrefix="ASPCookbook" TagName="PageHeader" 
                               Src="CH04UserControlHeaderVB.ascx" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
  <head>
    <title>User Control Display Header</title>
    <link rel="stylesheet" href="css/ASPNetCookbook.css">
  </head>
  <body>
    <form id="frmHeaderTest" method="post" runat="server">
      <table width="90%" align="center" border="0">
        <tr>
          <td class="PageHeading">Header Using Default Parameters:</td>
        </tr>
        <tr>
          <td><ASPCookbook:PageHeader id="pageHeader1" runat="server" />
          </td>
        </tr>
        <tr>
          <td class="PageHeading"><br /><br />
             Header With Parameters Set In ASPX:</td>
        </tr>
        <tr>
          <td><ASPCookbook:PageHeader id="pageHeader2" runat="server"
                                 headerImage="images/oreilly_header.gif" 
                                 dividerColor="#008000" 
                                 dividerHeight="12" />
          </td>
        </tr>
        <tr>
          <td class="PageHeading"><br /><br />
             Header With Parameters Set In Code-behind:</td>
        </tr>
        <tr>
          <td><ASPCookbook:PageHeader id="pageHeader3" runat="server" />
          </td>
        </tr>
      </table>
    </form>
  </body>
</html>

Example 4-5. Using the page header user control (.vb)

Option Explicit On 
Option Strict On
'-----------------------------------------------------------------------------
'
'   Module Name: CH04DisplayHeaderVB.aspx.vb
'
'   Description: This module provides the code behind for 
'                CH04DisplayHeaderVB.aspx
'
'*****************************************************************************
Imports System.Drawing

Namespace ASPNetCookbook.VBExamples
  Public Class CH04DisplayHeaderVB
    Inherits System.Web.UI.Page

    Protected pageHeader3 As ASPNetCookbook.VBExamples.CH04UserControlHeaderVB

    '*************************************************************************
    '
    '   ROUTINE: Page_Load
    '
    '   DESCRIPTION: This routine provides the event handler for the page load
    '                event.  It is responsible for initializing the controls 
    '                on the page.
    '-------------------------------------------------------------------------
    Private Sub Page_Load(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs) Handles MyBase.Load
      'initialize the 3rd page header user control
                        pageHeader3.headerImage = "images/ddig_logo.gif"
                        pageHeader3.dividerHeight = "18"
                        pageHeader3.dividerColor = ColorTranslator.ToHtml(Color.DarkBlue)
    End Sub  'Page_Load
  End Class  'CH04DisplayHeaderVB
End Namespace

Example 4-6. Using the page header user control (.cs)

//----------------------------------------------------------------------------
//
//   Module Name: CH04DisplayHeaderCS.ascx.cs
//
//   Description: This module provides the code behind for
//                CH04DisplayHeaderCS.ascx
//
//****************************************************************************
using System;
using System.Drawing;

namespace ASPNetCookbook.CSExamples
{
  public class CH04DisplayHeaderCS : System.Web.UI.Page
  {
    // controls on form
    protected ASPNetCookbook.CSExamples.CH04UserControlHeaderCS pageHeader3;

    //************************************************************************
    //
    //   ROUTINE: Page_Load
    //
    //   DESCRIPTION: This routine provides the event handler for the page 
    //                load event.  It is responsible for initializing the 
    //                controls on the page.
    //------------------------------------------------------------------------
    private void Page_Load(object sender, System.EventArgs e)
    {
      // initialize the 3rd page header user control
      pageHeader3.headerImage = "images/ddig_logo.gif";
      pageHeader3.dividerHeight = "18";
      pageHeader3.dividerColor = ColorTranslator.ToHtml(Color.DarkBlue);
    }  // Page_Load
  }  // CH04DisplayHeaderCS
}

Get ASP.NET Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.