User Controls
The previous section examined the powerful master page mechanism in ASP.NET. A master page allows the developer to define the structural layout for multiple Web Forms in a separate file and then apply this layout across multiple Web Forms. You can thus move common layout elements out of all the individual pages and into a single master page. As a consequence, the master page feature is a powerful mechanism for reducing code-behind and markup duplication across a Web application.
Yet, it still is possible, even when using a master page, for presentation-level (i.e., user interface) duplication to exist in a site. For instance, consider the page shown back in Figure 6.16. In this example, the feature book box is displayed only on the home page. But imagine that you want this box to appear on several other pages, but not on every page (if it was to appear on every page, you would place it in the master page). Your inner programmer should shirk at the idea of simply copying and pasting the markup and code for implementing this featured book box to multiple pages. Although such a solution is easy in the short term, maintaining this type of approach in the long run is a real headache; every time you have to make a change to this box, you have to change it in multiple places.
User controls are the preferred ASP.NET solution to this type of presentation-level duplication. They provide a cleaner approach to user interface reuse then copying and pasting or using the server-side includes of classic ASP. In addition, user controls in ASP.NET are very simple to create and then use. As well, they follow the same familiar development model as regular Web Forms.
Creating and Using User Controls
User controls are created in a manner similar to Web Forms. As with Web Forms, a user control can contain markup as well as programming logic. Also like Web Forms, the programming for a user control can be contained within the same file as the markup, or contained within a separate code-behind file. After a user control is defined, it can then be used in Web Forms, master pages, or even other user controls.
The markup for a user control is contained in a text file with the .ascx extension. This file can contain any necessary programming logic within embedded code declaration block (i.e., within <script runat="server">...</script> tags) embedded within this .ascx user control file. Alternately, the programming code can be contained in a code-behind class for the user control. However, the code-behind class for a user control inherits from the UserControl class, rather than the Page class.
Walkthroughs 6.3 and 6.4 demonstrate how to create and then use a simple user control.
Now that you have created a user control, you can use it in a Web Form, master page, or other user control. To make use of a user control, you must follow two steps:
Indicate that you want to use a user control via the Register directive, as shown in the following.
<%@ Register TagPrefix="SomePrefix" TagName="SomeName" Src="someControl.ascx" %>
TagPrefix determines a unique namespace for the user control, which is necessary to differentiate multiple user controls with the same name. TagName is the unique name for the user control, whereas Src specifies the virtual path to the user control, such as MyControl.ascx or ~/Controls/MyControl.ascx.
- After registering the user control, place the user control tag in the markup just as you would with any Web server control (including the runat="server" and Id properties). For instance, if you had the user control specified in step 1, the following markup adds this control.
<SomePrefix:SomeName id="myUC1" runat="server" />
Adding Data and Behaviors to the User Control
In the user control created in Walkthrough 6.3, the information on the featured book was hardcoded. A more realistic version of this user control would interact with some type of business object or database. Thus, like most Web Forms, most user controls also include some type of programming logic.
You also may want to customize some aspect of the user control, so that it appears or behaves differently when used in different pages or controls. For instance, in the example Featured Book user control, it might be useful to specify the category of book you want to see in the control. You can easily add this type of customization to a control, by adding public properties to the user control. These public properties can then be manipulated declaratively or programmatically by the containing page.
For instance, Listing 6.14 demonstrates the definition of a FeatureCategory property in the code-behind class for the FeatureBookControl user control. The Page_Load in this simplified example modifies the output of the control based on the value of this property.
Listing 6.14. FeatureBookControl.ascx.cs
public partial class FeatureBookControl : System.Web.UI.UserControl { // Data member for feature category property public string _category; protected void Page_Load(object sender, EventArgs e) { // Real-world example would use category values and content // from a database or business object. Here you // simply hardcode the values imgBook.ImageUrl = "~/images/"; if (FeatureCategory == "Programming") { labTitle.Text = "Framework Design Guidelines"; imgBook.ImageUrl += "0321246756.gif"; labDescription.Text = "This book can improve ..."; } else { labTitle.Text = "Core C# and .NET"; imgBook.ImageUrl += "0131472275.gif"; labDescription.Text = "Core C# and .NET is the ..."; } imgBook.AlternateText = "Cover image of " + labTitle.Text; } public string FeatureCategory { get { return _category; } set { _category = value; } } }
This code-behind class assumes that the markup for the FeatureBookControl user control has been modified, as shown in Listing 6.15.
Listing 6.15. FeatureBookControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="FeatureBookControl.ascx.cs" Inherits="FeatureBookControl" %> <h2>Featured Book</h2> <h3><asp:Label ID="labTitle" runat="server" /></h3> <asp:Image ID="imgBook" runat="server" CssClass="sideImage" /> <p> <asp:Label ID="labDescription" runat="server" /> </p>
This public property in the user control can now be used wherever you use this user control. For instance, the following example illustrates one way that this property could be used.
<uc:FeatureBookControl ID="myFeaturedBook" runat="server" FeatureCategory="Programming" />