5.1. 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:
Create a file with a .ascx extension.
Place the
@ Control
directive at the top of the file.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:
Create a user control code-behind class that inherits from the
UserControl
class.(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:
Register the control by using the
@ Register
directive at the top of the page.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 ...
Get ASP.NET 2.0 Cookbook, 2nd Edition 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.