How to Use ASP.NET 4 User Controls

How to Use ASP.NET 4 User Controls

Beginning ASP.NET 4 bookUser controls are great for encapsulating markup, controls, and code that you need repeatedly throughout your site. To some extent, they look a bit like server controls in that they can contain programming logic and presentation that you can reuse in your pages. However, rather than dragging existing ones from the VWD Toolbox, you need to create your own user controls and then add them to your ASPX pages, as you learn how to do later in this chapter.

Though master pages enable you to create content that is displayed in all pages in your site, it’s common to have content that should appear only on some but not all pages. For example, you may want to display a banner on a few popular pages, but not on the home page or other common pages. Without user controls, you would add the code for the banner (an image, a link, and so on) to each page that needs it. When you want to update the banner (if you want to use a new image or link), you need to make changes to all pages that use it. If you move the banner to a user control and use that control in your content pages instead, all you need to change is the user control, and the pages that use it pick up the change automatically. This gives you a flexible way to create reusable content.

User controls have the following similarities with normal ASPX pages:

  • They have a markup section where you can add standard markup and server controls.

  • They can be created and designed with Visual Web Developer in Markup, Design, and Split View.

  • They can contain programming logic, either inline or with a Code Behind file.

  • You have access to page-based information like Request.QueryString.

  • They raise some (but not all) of the events that the Page class raises, including Init, Load, and PreRender.

You should also be aware of a few differences. User controls have an .ascx extension instead of the regular .aspx extension. In addition, user controls cannot be requested in the browser directly. Therefore, you can’t link to them. The only way to use a user control in your site is by adding it to a content or master page or another user control (which eventually should be added to a page).

In the remainder of this chapter, you see how to create a user control that is capable of displaying banners. The user control is able to present itself as a horizontal or vertical banner to accommodate for differently sized regions in your pages. In the next section you see how to create a user control. The sections that follow show you how to use that control in an ASPX page.

Creating User Controls

User controls are added to the site like any other content type: through the Add New Item dialog box. Similar to pages, you get the option to choose the programming language and whether you want to place the code in a separate Code Behind file. Figure 8-1 shows the Add New Item dialog box for a user control.

ASP.NET 4 Add New User Control Item dialog box

Figure 8-1

Once you add a user control to the site, it is opened in the Document Window automatically. The first thing you may notice is that a user control doesn’t have an @ Page directive, but rather an @ Control directive as shown in this example that uses Code Behind:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs"

      Inherits="WebUserControl" %>

This marks the file as a user control, so the ASP.NET runtime knows how to deal with it. Other than that, the directive is identical to a standard ASPX page that doesn’t use a master page.

With the user control open in the VWD Document Window, you can use all the tools you have used in the previous seven chapters to create pages. You can use the Toolbox to drag controls in Markup and Design View, the CSS windows to change the look and feel and content of the user control, and the Properties Grid to change the properties of controls in your user controls. You can also write code that reacts to the events that the control raises.

To try this out yourself, the next exercise shows you how to create your first user control. In a later exercise you see how to use the control in ASPX pages in your site.

Creating a User Control

In this exercise, you create a basic user control that displays a single vertical banner using an Image control. In later exercises, you see how to use this control and how to add another (horizontal) image. You will then add some intelligence to the control so you can determine which of the two images to display at runtime.

For this exercise, you need two images that represent banners — one in portrait mode with dimensions of roughly 120 ¥ 240 pixels and one in landscape mode with a size of around 486 ¥ 60 pixels. The Resources folder for this chapter’s code download that comes with this book has these two images, but you could also create your own. Don’t worry about the exact size of the images; as long as they are close to these dimensions you should be fine.

1. Open the Planet Wrox site in VWD.

2. If you haven’t done so already, create a new folder called Controls in the root of the site. Although user controls can be placed anywhere in the site hierarchy, placing them in a separate folder makes them easier to find and manage.

3. Create another folder called Images at the root of the site.

4. Using Windows Explorer, open up the Resources folder for this chapter (at C:BegASPNETResourcesChapter 08 if you followed the instructions in the Introduction of this book). If you haven’t done so already, you can download the necessary resources from www.wrox.com. Drag (or copy and paste) the files Banner120x240.gif and Banner486x60.gif from Windows Explorer into the Images folder you created in Step 3. If you’re using your own images, drag them into the Images folder as well and give them the same names.

5. Right-click the Controls folder and choose Add New Item. In the dialog box that follows, choose your programming language, click Web User Control, and make sure that Place Code in Separate File is selected as shown in Figure 8-1. Name the file Banner and then click Add to add the control to the site. Notice how VWD adds the extension of .ascx for you automatically if you don’t type it in. VWD does this for all file types you add through the Add New Item dialog so you don’t need to type the extension yourself. Your Solution Explorer should now look like Figure 8-2.

ASP.NET 4 Visual Web Developer 2010 Solution Explorer

Figure 8-2

6. Switch the user control to Design View and drag a Panel from the Standard category of the Toolbox onto the design surface. Using the Properties Grid, change the ID of the Panel to VerticalPanel.

7. From the Toolbox, drag an Image control into the Panel. Select the Image and then open the Properties Grid. Locate the ImageUrl property and click its ellipsis button, shown in Figure 8-3.

Figure 8-3

Browse to the Images folder, select the Banner120x240.gif image, and click OK to add it to the user control. Your Design View now looks like Figure 8-4.

8. Using the same Properties Grid, locate the AlternateText property and type This is a sample banner. Some browsers, like Firefox and Internet Explorer 8 and later, display the alternate text (rendered as a client-side alt attribute) only when the image cannot be displayed correctly. Other browsers including older versions of Internet Explorer show the alternate text as the tooltip for the image when you hover your mouse over it.

Figure 8-4

9. Switch to Markup View and if your Panel control has Height and Width attributes that were added by default when you dragged it on the page, remove both of them.

10. Wrap the Image in a standard <a /> element and set its href attribute to http://p2p.wrox.com. If you want, you can use the a code snippet to insert the bare link for you. To do this, type the letter a and then press Tab. VWD inserts a link for you and enables you to directly type in the href value. When you then press Tab again, the content of the link is selected, which you can delete by pressing Del (the Image control will be the contents of the link). Finally, cut the closing </a> tag and move it to after the image.

11. Set the target of the anchor tag (<a>) to _blank to force the browser to open up the page in a new window when the image is clicked. When you’re done, the code for the entire user control should look like the following code, except for the Language attribute that you may have set to VB and the AutoEventWireup that is False by default in VB.NET:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Banner.ascx.cs"

       Inherits="Controls_Banner" %>

<asp:Panel ID="VerticalPanel" runat="server">

  <a href="http://p2p.wrox.com" target="_blank">

    <asp:Image ID="Image1" runat="server" AlternateText="This is a sample banner"

            ImageUrl="~/Images/Banner120x240.gif" />

  </a>

</asp:Panel>

12. Save the changes by pressing Ctrl+S and then close the user control file by pressing Ctrl+F4.

How It Works

The design experience of user controls in the Visual Web Developer IDE is identical to that of pages. You can use drag and drop, the Toolbox, the Markup, Split, and Design Views, and so on. This makes it easy to work with user controls because you can use all the familiar tools you also use for page development.

The control you just created displays a single image wrapped in an anchor element. In the next section you see how to add the user control to the master page so it will be displayed in the sidebar <div> of every page in the site. Later sections in this chapter show you how to add the other image that can be used to display a horizontal banner in individual content pages.

Adding User Controls to a Content Page or Master Page

To be able to use a user control in a content or master page or in another user control, you need to perform two steps. First, you need to register the control by adding an @ Register directive to the page or control where you want the user control to appear. The second step involves adding the tags for the user control to the page and optionally setting some attributes on it. 

A typical @ Register directive for a user control looks like this:

<%@ Register Src="ControlName.ascx" TagName="ControlName" TagPrefix="uc1" %>

The directive contains three important attributes, described in the following table.

Attribute
Description
Src
Points to the user control you want to use. To make it easier to move pages at a later stage, you can also use the tilde (~) syntax to point to the control from the application root.
TagName
The name for the tag that is used in the control declaration in the page. You’re free to make up this name, but usually it is the same as the name of the control.
TagPrefix
Holds the prefix of the TagName that is used in the control declaration. Just as ASP.NET uses the asp prefix to refer to its controls, you need to provide a prefix for your own user controls. By default, this prefix is uc followed by a sequential number, but you can also change it to your own liking — for example, to your own company name or a custom abbreviation.

Considering the user control you created in the preceding exercise, your @ Register directive could look like this:

<%@ Register Src="~/Controls/Banner.ascx" TagName="Banner" TagPrefix="uc1" %>

When the control is registered, you can add it to the page using the TagPrefix:TagName construct, similar to the way you add standard server controls to a page. Given the @ Register directive for the banner control you need the following markup to add the control to your page:

<uc1:Banner ID="Banner1" runat="server" />

This is the minimum code needed for a user control in a page. Note that the control is defined by a combination of the TagPrefix and the TagName. The other two attributes — ID and runat — are standard attributes that most controls in an ASP.NET page have.

Fortunately, in most cases, you don’t have to type all this code yourself. When you drag a user control from the Solution Explorer into a page in Design View, VWD adds the required code for you automatically. The following exercise demonstrates how this works.

Adding the User Control to Your Page

In this exercise you add the user control Banner.ascx to the master page, so it displays a banner on each page in the site in the sidebar area.

1. Open up Frontend.master from the MasterPages folder and switch it into Design View.

2. Locate the drop-down list that enables you to select a theme, position your cursor right after the drop-down list, and press Enter three times to create some room.

3. From the Solution Explorer, drag the file Banner.ascx from the Controls folder into the empty spot you just created. Design View is updated and now looks like Figure 8-5.

Figure 8-5

If your Design View doesn’t look like this, but looks much closer to how the file ends up in the browser, you may still have the styleSheetTheme set in the web.config file. Also, you may have more or fewer options selected in the View Ø Visual Aids or View Ø Formatting Marks menu, which may affect your display.

4. Switch to Markup View and locate the @ Register directive at the top of the file. Change the two dots in the src attribute to a tilde (~):

<%@ Register Src="~/Controls/Banner.ascx" TagName="Banner" TagPrefix="uc1" %>

5. Save the changes to the master page and close it.

6. Open the file Monochrome.css from its theme folder and add the following CSS declaration:

img

{

  border: 0;

}

7. Copy this declaration to the other theme (add it to DarkGrey.css).

8. Save all your changes, right-click Default.aspx in the root of your site in the Solution Explorer, and choose View in Browser.

9. The banner is now displayed below the drop-down list. Switch to the other theme and you’ll see the same banner appear. When you click the banner, a new window is opened that takes you to the site you linked to in the previous exercise.

How It Works

When you dragged the user control onto the design surface of the master page, VWD performed two tasks: first it added the @ Register directive to tell the page where to look for the user control. It then added the control declaration right below the drop-down list.

When the page loads, the ASP.NET runtime sees the control declaration and injects the output of the control at the specified location. In this example, the Panel, the <a /> element, and the Image are inserted in the sidebar region of the page. If you look at the HTML for the page in the browser, you see the following code:

</select>

<br /><br /><br />

<div id="Banner1_VerticalPanel">

  <a href="http://p2p.wrox.com" target="_blank">

    <img id="Banner1_Image1" src="Images/Banner120x240.gif"

           alt="This is a sample banner" />

  </a>

</div>

The Panel control has been transformed into an HTML <div /> element and the Image control into an <img /> element. Because the anchor element (<a />) was defined with plain HTML in the user control, it ends up exactly as you wrote it.

Notice how the id of the panel has been changed from VerticalPanel to the client ID Banner1_VerticalPanel. This is necessary to give the <div> tag a unique client-side id attribute that is used in client-side scripting. The same has happened to the id of the <img /> element. You see more about this in a later section of this chapter.

Normally when you put an <img /> element inside an <a /> element to link it, the browser draws a border around the image. The border is usually blue for unvisited links and purple for links you have visited before. To remove that border, you need to add the following CSS:

img

{

  border: none;

}

Earlier versions of ASP.NET automatically injected the border property with a border-width of zero pixels (making it invisible) as an inline style on the <img> tag. Because inline style sheets overrule embedded and external style sheets, this made it difficult to influence the border from your own CSS if you wanted to change it again. Fortunately, this issue has been fixed in ASP.NET 4. You now have more control over borders around images, but need to explicitly remove them if you don’t want them using the CSS shown here.

When you add a user control to a page, VWD by default refers to the control using a relative path. In this exercise, this path first contained two dots (..) to indicate the parent folder, followed by the Controls folder, and finally by the name of the control:

<%@ Register Src="../Controls/Banner.ascx" TagName="Banner" TagPrefix="uc1" %>

By changing the two dots to the tilde symbol, it becomes easier to move your pages around in your site because the src attribute now always points to the Controls folder at the application’s root, no matter where the page that consumes the control is located.

Though the tilde syntax makes your pages with user controls a little easier to manage, there is an even easier way to register your user controls site-wide.

This article is excerpted from chapter 8 "User Controls" of the book Beginning ASP.NET 4: in C# and VB by Imar Spaanjaars (ISBN: 978-0-470-50221-1, Wrox, 2010, Copyright Wiley Publishing Inc.)

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *