Recipe 5.2. Sharing a Page Header on Multiple Pages


Problem

You have a header 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 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 control the basic look of the header programmatically.

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 5-1. (The second divider line appears in green and the third divider line appears in blue when rendered on the screen.) Example 5-1 shows the .ascx file for the user control. Examples 5-2 and 5-3 show the VB and C# code-behind files for the user control. Example 5-4 shows the .aspx file that uses the user control in the three different ways previously mentioned. Examples 5-5 and 5-6 show the VB and C# code-behind files for the test page that uses the user control.

Discussion

User controls provide an easy way to partition pages and reuse the page sections throughout your application. They are 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 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 control the basic look of the header programmatically.

The HTML for the user control (see Example 5-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.

Figure 5-1. Page header user control output


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 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 define the "custom tag" uniquely on the ASP.NET page. The TagPrefix is typically set to the project's namespace. The TagName should be set to a value that describes the control's use. 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="/books/1/505/1/html/2/CH05UserControlHeaderVB.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  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  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.NET server control. You can set the appropriate values in Page_Load or another method. Here's how we do it in our example:

 

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

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

See Also

Recipe 1.1 for how to use master pages to share common HTML between pages

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

 <%@ Control Language="VB" AutoEventWireup="false" CodeFile="CH05UserControlHeaderVB.ascx.vb" Inherits="ASPNetCookbook.VBExamples.CH05UserControlHeaderVB" %> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td align="center"> <img  runat="server" src="/books/1/505/1/html/2/images/ASPNetCookbookHeading_blue.gif" alt="ASPNETCookbook"/> </td> </tr> <tr> <td  runat="server" bgcolor="#6B0808" height="6"> <img src="/books/1/505/1/html/2/images/spacer.gif" alt="divider"/></td> </tr> </table> 

Example 5-2. Page header user control (.vb)

 Option Explicit On Option Strict On Imports System.Web.UI.WebControls Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code behind for ''' CH05UserControlHeaderVB.ascx ''' </summary> Partial Class CH05UserControlHeaderVB Inherits System.Web.UI.UserControl '''*********************************************************************** ''' <summary> ''' This property provides the ability get/set the image used in the ''' header user control ''' </summary> Public Property headerImage() As String Get Return (imgHeader.Src) End Get Set(ByVal Value As String) imgHeader.Src = Value End Set End Property 'headerImage '''*********************************************************************** ''' <summary> ''' This property provides the ability get/set the divider color used ''' at the bottom of the user control ''' </summary> Public Property dividerColor() As String Get Return (tdDivider.BgColor) End Get Set(ByVal Value As String) tdDivider.BgColor = Value End Set End Property 'dividerColor '''*********************************************************************** ''' <summary> ''' This property provides the ability get/set the divider height used ''' at the bottom of the user control ''' </summary> Public Property dividerHeight() As String Get Return (tdDivider.Height) End Get Set(ByVal Value As String) tdDivider.Height = Value End Set End Property 'dividerHeight '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the page load event. It ''' is responsible for initializing the controls on the page. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub Page_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load 'place user code here End Sub 'Page_Load End Class 'CH05UserControlHeaderVB End Namespace 

Example 5-3. Page header user control (.cs)

 using System; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code behind for /// CH05UserControlHeaderCS.ascx  /// </summary> public partial class CH05UserControlHeaderCS : System.Web.UI.UserControl { ///*********************************************************************** /// <summary> /// This property provides the ability get/set the image used in the /// header user control /// </summary> public String headerImage { get { return imgHeader.Src; } set { imgHeader.Src = value; } } // headerImage ///*********************************************************************** /// <summary> /// This property provides the ability get/set the divider color used /// at the bottom of the user control /// </summary> public String dividerColor { get { return tdDivider.BgColor; }     set { tdDivider.BgColor = value; } } // dividerColor ///*********************************************************************** /// <summary> /// This property provides the ability get/set the divider height used /// at the bottom of the user control /// </summary> public String dividerHeight { get { return tdDivider.Height; } set { tdDivider.Height = value; } } // dividerHeight ///*********************************************************************** /// <summary> /// This routine provides the event handler for the page load event. /// It is responsible for initializing the controls on the page. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void Page_Load(object sender, EventArgs e) { // place user code here } // Page_Load } // CH05UserControlHeaderCS } 

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

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master" AutoEventWireup="false" CodeFile="CH05DisplayHeaderVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH05DisplayHeaderVB" Title="User Control Display Header" %> <%@ Register TagPrefix="ASPCookbook" TagName="PageHeader"    src="/books/1/505/1/html/2/CH05UserControlHeaderVB.ascx" %> <asp:Content  Runat="server" ContentPlaceHolder> <br /> <br /> <table width="90%" align="center" border="0"> <tr> <td >Header Using Default Parameters:</td> </tr> <tr> <td> <ASPCookbook:PageHeader  runat="server" /> </td> </tr> <tr> <td ><br /><br /> Header With Parameters Set In ASPX:</td> </tr> <tr> <td> <ASPCookbook:PageHeader  runat="server" headerImage="images/oreilly_header.gif" dividerColor="#008000" dividerHeight="12" /> </td> </tr> <tr> <td > <br /><br /> Header With Parameters Set In Code-behind:</td> </tr> <tr> <td> <ASPCookbook:PageHeader  runat="server" /> </td> </tr> </table> </asp:Content> 

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

 Option Explicit On Option Strict On Imports System.Drawing Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code behind for ''' CH05DisplayHeaderVB.aspx ''' </summary> Partial Class CH05DisplayHeaderVB   Inherits System.Web.UI.Page   '''********************************************************************   ''' <summary>   ''' This routine provides the event handler for the page load event. It   ''' is responsible for initializing the controls on the page.   ''' </summary>   '''   ''' <param name="sender">Set to the sender of the event</param>   ''' <param name="e">Set to the event arguments</param>   Protected Sub Page_Load(ByVal sender As Object, _   ByVal e As System.EventArgs) Handles Me.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 'CH05DisplayHeaderVB End Namespace 

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

 using System; using System.Drawing; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code behind for /// CH05DisplayHeaderCS.aspx /// </summary> public partial class CH05DisplayHeaderCS : System.Web.UI.Page { ///*********************************************************************** /// <summary> /// This routine provides the event handler for the page load event. /// It is responsible for initializing the controls on the page. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void Page_Load(object sender, 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  } // CH05DisplayHeaderCS } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net