Chapter 7. Creating Custom Controls with User Controls

A web User control enables you to build a new control from existing controls. By taking advantage of User controls, you can easily extend ASP.NET Framework with your own custom controls.

Imagine, for example, that you need to display the same address form in multiple pages in a web application. The address form consists of several TextBox and Validation controls for entering address information. If you want to avoid declaring all the TextBox and Validation controls in multiple pages, you can wrap these controls inside a web User control.

Anytime you discover that you need to display the same user interface elements in multiple pages, you should consider wrapping the elements inside a User control. By taking advantage of User controls, you make your website easier to maintain and extend.

In this chapter, you learn how to build custom controls with User controls by starting with the basics. You learn how to create a simple User control and expose properties and events from the User control.

You then examine how you can use AJAX with a User control. You learn how to modify the content displayed by a User control without posting the page that contains the User control back to the web server.

Finally, you learn how you can load User controls dynamically. You learn how to load a User control at runtime and inject the User control into a page. In the final section of this chapter, dynamically loaded User controls are used to build a multipage wizard.

Creating User Controls

Let’s start by building a simple User control that randomly displays one image from a folder of images (see Figure 7.1). The code for the User control is contained in Listing 7.1.

Figure 7.1. Displaying an image with the RandomImage User control.

image

Listing 7.1. RandomImage.ascx

images

images

Visual Web Developer Note

You create a new User control in Visual Web Developer by selecting website, Add New Item, and the Web User control item.

The file in Listing 7.1 closely resembles a standard ASP.NET page. Like a standard ASP.NET page, the User control contains a Page_Load() event handler. Also, the User control contains standard controls such as ASP.NET Image and Label controls.

User controls are closely related to ASP.NET pages. Both the UserControl class and the Page class derive from the base TemplateControl class. Because they derive from the same base class, they share many of the same methods, properties, and events.

The important difference between an ASP.NET page and a User control is that a User control is something you can declare in an ASP.NET page. When you build a User control, you build a custom control.

The file in Listing 7.1 ends with the .ascx extension. You cannot request this file directly from a web browser. To use the RandomImage User control, you must declare the control in an ASP.NET page.

The page in Listing 7.2 contains the RandomImage User control. When you open the page, a random image displays.

Listing 7.2. ShowRandomImage.aspx

images

Before you can use a web User control in a page, you must register it. The page in Listing 7.2 includes a <%@ Register %> directive that contains the following three attributes:

TagPrefixIndicates the namespace that you want to associate with the User control for the current page. You can use any string that you want.

TagNameIndicates the name that you want to associate with the User control for the current page. You can use any string that you want.

SrcIndicates the virtual path to the User control (the path to the .ascx file).

The RandomImage User control is declared in the body of the page. It looks like this:

<user:RandomImage ID="RandomImage1" Runat="Server" />

The declaration of the User control uses the TagPrefix and TagName specified in the <%@ Register %> directive. Furthermore, you provide a User control with both an ID and a Runat attribute, just as you would for any standard ASP.NET control.

Visual Web Developer Note

You can add a User control to a page in Visual Web Developer simply by dragging the User control from the Solution Explorer window onto the Design surface. The <%@ Register %> directive is automatically added to the source of the page.

Registering User Controls in the Web Configuration File

As an alternative to registering a User control in each page in which you need to use it by using the <%@ Register %> directive, you can register a User control once for an entire application. You can register a User control in an application’s web configuration file.

For example, the web configuration file in Listing 7.3 registers the RandomImage control for the application.

Listing 7.3. Web.Config

images

After you register a User control in the web configuration file, you can simply declare the User control in any page. For example, the page in Listing 7.4 contains an instance of the RandomImage User control, but it does not include the <%@ Register %> directive.

Listing 7.4. ShowAppRegister.aspx

images

You need to be aware of one important limitation when registering a User control in the web configuration file. A User control cannot be located in the same folder as a page that uses it. For that reason, you should create all your User controls in a subfolder.

Exposing Properties from a User Control

The RandomImage User control always displays an image from the Images folder. It would be nice if you could specify the name of the folder that contains the images so that you could use different folder paths in different applications. You can do this by exposing a property from the RandomImage User control.

The modified RandomImage control in Listing 7.5, named PropertyRandomImage, exposes a property named ImageFolderPath.

Listing 7.5. PropertyRandomImage.ascx

images

images

After you expose a property in a User control, you can set the property either declaratively or programmatically. The page in Listing 7.6 sets the ImageFolderPath property declaratively.

Listing 7.6. ShowDeclarative.aspx

images

The PropertyRandomImage User control in Listing 7.6 includes an ImageFolderPath property. When you request the page, the random images are retrieved from the Images2 folder.

Visual Web Developer Note

Any properties that you add to a User control appear in both Intellisense and the Property window.

The page in Listing 7.7 demonstrates how you can set the ImageFolderPath programmatically.

Listing 7.7. ShowProgrammatic.aspx

images

The page in Listing 7.7 includes a Page_Load() event handler. This handler programmatically sets the ImageFolderPath to the value Images2.

Exposing Events from a User Control

You can expose custom events from a User control. After you expose the event, you can handle the event in the page that contains the User control.

Exposing events is useful when you need to pass information up to the containing page. Imagine, for example, that you want to create a custom tab strip with a User control. When a user clicks a tab, you want to change the content displayed in the page (see Figure 7.2).

Figure 7.2. Displaying a tab strip with a User control.

image

The User control in Listing 7.8 contains the code for a simple tab strip.

Listing 7.8. TabStrip.ascx

images

images

images

The tab strip is created with the help of a DataList control. The DataList control displays links for each of the items created in the Page_Load() event handler.

The TabStrip control exposes an event named TabClick. This event is raised in the dlstTabStrip_SelectedIndexChanged() event handler when a user clicks a tab.

The page in Listing 7.9 uses the TabStrip control to display different content depending on the tab selected.

Listing 7.9. ShowTabStrip.aspx

images

images

images

The page in Listing 7.9 includes an event handler for the TabStrip control’s TabClick event. When you click a tab, the index of the selected tab is retrieved from the tab strip, and the View control with the matching index displays.

Visual Web Developer Note

You can add a TabClick event handler to the TabStrip control by selecting the TabStrip control from the top-left drop-down list and selecting the TabClick event from the top-right drop-down list.

Note

The ASP.NET Framework includes a Menu control that you can use to create both tabstrips and pop-up menus. This control is discussed in Chapter 4, “Using the Rich Controls,” and Chapter 22, “Using the Navigation Controls.”

Creating an AddressForm Control

Let’s end this section by creating a generally useful Web User control. We build an AddressForm User control that you can reuse in multiple pages or reuse multiple times in a single page (see Figure 7.3).

Figure 7.3. Displaying multiple address forms with the AddressForm User control.

image

The AddressForm User control is contained in Listing 7.10.

Listing 7.10. AddressForm.ascx

images

images

images

images

images

The AddressForm control contains form controls for entering your street, city, state, and postal code. Each of these fields is validated by a RequiredFieldValidator control. Finally, the AddressForm includes a Label that can provide a title for the control.

The AddressForm exposes all its form fields with properties. The control includes public Street, City, State, and PostalCode property, which you can read from the containing page.

The page in Listing 7.11 illustrates how you can use the AddressForm control in a page.

Listing 7.11. Checkout.aspx

images

images

images

images

The page in Listing 7.11 contains two instances of the AddressForm control: a Billing Address and Shipping Address. When you click the Button control, the address information is retrieved from the AddressForm controls and displayed in a Literal control. (In a real application, you would grab the data and store it in a database.)

Web Standards Note

The AddressForm User control does not use an HTML table to lay out its controls. You should strive to avoid using tables except when displaying tabular information. Instead, Cascading Style Sheet (CSS) rules are used to position the form elements.

AJAX and User Controls

Ajax (Asynchronous JavaScript and XML) enables you to update content in a page without posting the page back to the server. Behind the scenes, AJAX uses the XMLHttp ActiveX component (in the case of Microsoft Internet Explorer 6.0) or the XMLHttpRequest intrinsic browser object (in the case of other browsers such as FireFox and Internet Explorer 8.0).

We explore the topic of Ajax in depth in Part IX, “ASP.NET AJAX.” In this section, I want to provide you with a quick sample of using Ajax with a User control. The User control in Listing 7.12 randomly displays one of three quotations. The quotation is updated automatically every 5 seconds (see Figure 7.4).

Figure 7.4. Using AJAX to display a random quotation.

image

Listing 7.12. RandomQuotation.ascx

images

A random quotation is assigned to the Label control in the Page_Load() method in Listing 7.12. The Label control is contained in an UpdatePanel control. The UpdatePanel marks an area of the page that is refreshed without a postback (an Ajax zone). The UpdatePanel control is associated with a Timer control. The Timer control causes the UpdatePanel to refresh its content every 5 seconds (an interval of 5,000 milliseconds).

The page in Listing 7.13 illustrates how you can use the RandomQuotation User control. It contains the User control and also displays the current time.

Listing 7.13. ShowRandomQuotation.aspx

images

images

The random quotation is updated, but the time on the page does not change. Only the area of the page that contains the random quotation is updated.

Dynamically Loading User Controls

You can dynamically load a User control at runtime and display it in a page. Imagine, for example, that you want to display different featured products randomly on the home page of your website. However, you want to display each featured product with a completely different layout. In that case, you can create a separate User control for each product and load one of the User controls randomly at runtime.

You load a User control with the Page.LoadControl() method, which returns an instance of the Control class that you can add to a page. Typically, you add the User control to a PlaceHolder control that you have declared on the page.

Note

The PlaceHolder control was designed to do absolutely nothing. It simply acts as a placeholder on the page where you can add other controls.

For example, the page in Listing 7.14 randomly loads one of the controls from the FeaturedProducts folder and adds the control to the page.

Listing 7.14. ShowFeaturedProduct.aspx

images

images

Using the Reference Directive

When you load a User control with the Page.LoadControl() method, the User control is returned as an instance of the System.Web.UI.Control class. This means that if the User control includes any custom properties, the properties aren’t available when you dynamically load the User control.

If you dynamically load a User control, you need to cast the control to the correct type before you can access any of the control’s custom properties. To get a reference to a User control’s type, you must use the <%@ Reference %> directive.

For example, imagine that you need to create a form that displays different questions depending on the answers that a user provides for previous questions. In that case, you can dynamically load different User controls that contain the different sets of questions.

For example, the page in Listing 7.15 contains a survey form. The first question asks you whether you currently use ASP Classic or ASP.NET. Depending on your answer, the remainder of the form displays different questions (see Figure 7.5).

Figure 7.5. Displaying a survey form with dynamically loaded questions.

image

Listing 7.15. WebSurvey.aspx

images

images

images

images

Web Standards Note

The DropDownList control in Listing 7.15 reloads the page automatically when you select a new option. You should never reload a page without warning the user because this can be confusing for someone who uses an assistive device such as a screen reader. In Listing 7.15, a warning is added to the ToolTip property of the DropDownList control.

Depending on the user’s selection from the DropDownList control, one of two User controls is loaded in the Page_Load() event handler: ASPSurvey.ascx or ASPNetSurvey.ascx. These controls are contained in Listing 7.16 and Listing 7.17.

When you submit the survey form, the btnSubmit_Click() method executes. This method casts the User control loaded in the form to the correct type. It casts the User control to either the ASPSurvey or the ASPNetSurvey type.

The page in Listing 7.16 includes two <%@ Reference %> directives. These reference directives enable you to cast the User control to the correct type so that you can access custom properties of the control such as the KnowSlow and KnowOutdated properties.

Listing 7.16. ASPSurvey.ascx

images

Listing 7.17. ASPNetSurvey.ascx

images

Creating a Multipage Wizard

This final section discusses how you can create a multipage wizard by dynamically loading different User controls into the same page. This is going to be a complicated sample, but it is a realistic sample of situations when you would want to load User controls dynamically (see Figure 7.6).

Figure 7.6. Displaying a wizard with a series of User controls.

image

Imagine that you must create a form with 200 questions in it. Displaying all 200 questions to a user in a single form would be overwhelming. Instead, it makes more sense to break the form into multiple pages. Each page of questions can be represented with a User control.

First, you need to define an interface, named the IWizardStep interface, which all the User controls will implement. An interface enables you to know, in advance, that a User control supports a particular set of properties or methods.

Note

You need to add the interface in Listing 7.18 to your application’s App_Code folder. In Visual Web Developer, create the interface by selecting Website, Add New Item, select Class. Visual Web Developer prompts you to create the App_Code folder.

The IWizardStep interface is contained in Listing 7.18.

Listing 7.18. IWizardStep.cs

images

The interface in Listing 7.18 contains two methods: LoadStep() and NextStep(). The LoadStep() method is called when a User control is first loaded. The NextStep() method is called when the Next button is clicked in the wizard.

The NextStep() method returns a Boolean value. If the NextStep() method returns the value False, the user doesn’t advance to the next wizard step.

This wizard consists of the three wizard steps contained in Listing 7.19, Listing 7.20, and Listing 7.21.

Listing 7.19. WizardStepsStep1.ascx

images

images

The wizard step in Listing 7.19 contains a simple form that contains Textbox controls for the user’s first and last name. Both TextBox controls are validated with RequiredFieldValidator controls.

The User control in Listing 7.19 implements the IWizardStep interface. It contains an <%@ Implements %> directive at the top of the control.

The LoadStep() method assigns values to the txtFirstName and txtLastName TextBox controls from Session state. The NextStep() method grabs the values from the txtFirstName and txtLastName TextBox controls and assigns the values to Session state.

The second step of the Wizard is contained in Listing 7.20.

Listing 7.20. WizardStepsStep2.ascx

images

images

The User control in Listing 7.20 also implements the IWizardStep interface. In this step, the user enters a favorite color.

The final wizard step is contained in Listing 7.21.

Listing 7.21. WizardStepsStep3.ascx

images

The wizard step in Listing 7.21 displays a summary of answers that the user has provided in the first two wizard steps (see Figure 7.7). It also implements the IWizardStep interface. Because this is the final wizard step, the NextStep() method always returns the value False.

Figure 7.7. Displaying the wizard summary step.

image

The page in Listing 7.22 contains the actual wizard. This page loads each of the wizard steps.

Listing 7.22. Wizard.aspx

images

images

images

images

images

The list of wizard steps is created in the Page_Load() method. The path to each wizard step User control is added to a collection of wizard steps.

The StepIndex property represents the index of the wizard step to display. The value of this property is stored in ViewState so that the value is available across multiple page requests.

The current wizard step is loaded by the LoadWizardStep() method. This method uses the StepIndex to grab the path to the current wizard step. Next, it uses the Page.LoadControl() method to actually load the wizard step User control.

After the LoadWizardStep() method loads the current wizard step, it calls the control’s LoadStep() method and initializes the control.

The page also contains a Previous and Next button. When you click the Previous button, the btnPrevious_Click() method is called and the StepIndex is reduced by one. When you click the Next button, the btnNext_Click() method is called.

The btnNext_Click() method first calls the current wizard step’s NextStep() method. If this method returns the value True, one is added to the StepIndex property, and the next wizard step is loaded. Otherwise, if the NextStep() method returns false, the next wizard step is not loaded.

Summary

In this chapter, you learned how to build custom controls by creating User controls. The first section covered the basics of User controls. You learned how to create a User control and register it both in a page and in a Web configuration file. You learned how to add custom properties and events to a User control.

The next topic was caching and User controls. You learned how to cache the rendered content of a User control in server memory. You also learned how to share the same cached content across multiple pages.

You also explored the topic of AJAX and User controls. You learned how to update content in a User control without posting the page that contains the User control back to the web server.

Finally, you learned how to add User controls dynamically to a page. You learned how to use the <%@ Reference %> directive to cast a User control to a particular type. You also saw a series of User controls loaded dynamically to create a multipage wizard.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset