The ASP Column: HTMLControls and WebControls in ASP .NET

MSDN Magazine

HTMLControls and WebControls in ASP .NET
George Shepherd
Download the code for this article:ASP0109.exe (79KB)
Browse the code for this article at Code Center:ASPX_Controls

A

SP .NET has lots to offer developers over previous versions of ASP. One of the major benefits of ASP .NET is its native server-side controls. This month I will investigate the two kinds of ASP .NET server-side controls: HTMLControls and WebControls. I'll also focus on the motivation for them.

Life Without Server-side Controls

      To illustrate the power of server-side controls, I'll develop a Web page that pairs specific types of electric guitars with specific amplifiers and then displays some information about the combinations. To begin, let's see how you might develop a page like this in classic ASP. Figure 1 shows a browser view of the completed raw ASP page. You select a guitar and an amplifier from the comboboxes, then press the Information button. The code matches the guitar and amp, then displays some relevant information about the combination.

Figure 1 Classic ASP Page
Figure 1Classic ASP Page

      Just implementing the simple page shown in Figure 1 turns out to be a verbose exercise in ASP coding. Figure 2 shows the ASP code that's required.
      When you write an ASP file, you're telling the ASP DLL to generate very specific HTML for the browser. In the example I just showed, the code indicates which HTML tags and text the browser will receive to list some guitars and amplifiers in a combobox and an input button. The ASP DLL pushes the <html>, <body>, and <form> tags out to the browser, followed by the heading "Axe 'n' Stacks". Next, the ASP page pushes out the standard <select> tag to tell the browser to display a combobox.
      There's a lot of code required just to show the selected item in the combobox. You need a bunch of if...then JavaScript statements to figure out which specific item the user selected from the comboboxes. Finally, the code block at the bottom checks for a Les Paul/Marshall combination or a Stratocaster/Marshall combination—used by Jimmy Page and Jimi Hendrix, respectively. While this code may seem a bit verbose, this sort of functionality (dynamic content) is nearly impossible with raw HTML.
      Take a look at Figure 3, which shows the code that's generated for the browser when the ASP page is hit. The select tag shows the list of possible selections, along with the one that was actually selected.
      The fundamental problem here is that HTTP is a connectionless (therefore stateless) protocol. When you program comboboxes, radio buttons, and checkboxes for a desktop application, it turns out that it is fairly easy to keep track of the state of the controls. All of the code lives under one roof and only one user is hitting on the application.
      Not so in Web development. Since the Web is based on HTTP, a connectionless protocol, it's likely that each hit on your page comes from a different user. Consequently, it's up to you as a developer to keep track of the state of the controls for each session. In the case of the checkboxes for a desktop application, it's a matter of checking the query string that comes back and parsing out the control value. The code marks the item as <selected> if it's the one that came back from the client. (Notice the code checks to see whether the user selected "Les Paul", then adjusts the state of the selection control accordingly.)
      It would be great if some infrastructure code took care of these mundane details. Fortunately, ASP .NET introduces server-side controls for just this reason.

ASP .NET Server-side Controls

      Classic ASP is all about mixing executable code with HTML so that a page is generated dynamically. Every time a request is submitted to the server, the server generates the appropriate HTML response. Unfortunately, the code for managing controls often ends up looking like early efforts at nonstructured Basic programming from those cheap programming books that were published in the early 1980s.
      As I've shown, classic ASP Web processing involves extracting form elements and repopulating controls manually. ASP .NET introduces server-side controls to make programmatic access to these controls more straightforward. Because HTTP is a connectionless protocol, managing control state can be a real headache. Server-side controls help solve this problem by retaining their state between postbacks. This allleviates the problem of constantly having to write the HTML code regeneration by hand.
      Programming a page using server-side controls is rather like programming a desktop application. You can expect the state of a control to remain constant during the life of a desktop program. Server-side controls make the same thing happen on a Web page, even though the UI is widely distributed.
      As mentioned earlier, ASP .NET introduces two kinds of control abstractions: HTMLControls and WebControls. These control classes wrap control management. Rather than pushing the control tags out to the browser by hand, you use the HTMLControls or the WebControls to do that for you. They keep track of the state of the control between sessions, displaying images and other minutiae so you can leave work and go home before the classic ASP programmers do. Let's start with HTMLControls.

HTMLControls

      The ASP .NET HTMLControls and WebControls are fully qualified common language runtime (CLR)-based classes. They derive from System.Object just like all the other CLR classes do, and they have fields, methods, and delegates/events just like other CLR classes. Their primary function is to manage controls on a Web page.
      HTMLControls represent practically a one-to-one mapping between the normal HTML tags you might see on a page and the CLR-based classes that manage them. For example, when ASP .NET sees you declaring a button tag on your ASP page, ASP .NET wraps it in an HtmlButton class. Then, when you need programmatic access to that button, you can just access the methods and member variables of the HtmlButton object representing that tag. Figure 4 shows a rundown of the various HTMLControls available within ASP .NET.
      Figure 5 shows the Axe 'n' Stacks page built using ASP .NET HTMLControls. Notice the placement of the selection, button, textarea, and image tags that look rather like classic ASP. When ASP .NET comes across these tags, it maps them to the appropriate HTMLControls. The input button ("information") is wired to a handler named FetchInfo_Click. FetchInfo_Click refers to the controls declared near the bottom of the page. However, notice the way FetchInfo_Click manages the control by accessing the form's other fields. The handler examines the incoming guitar/amp combination and fills the textarea with the blurb. Then the handler sets up the image controls to display the correct guitar and amp image files (JPEGs in this case). Figure 6 shows the Web page with images displayed.

Figure 6 Web Page Showing Guitar and Amp
Figure 6Web Page Showing Guitar and Amp

      Basically, whenever you declare controls on your page in the normal ASP manner, and they are marked as runat=server, ASP .NET wraps them using HTMLControls.

WebControls

      For the most part, WebControls perform the same function as HTMLControls—that is, making your life easier as a Web page developer. Many of the WebControls map to the normal HTML control tags. However, the WebControls expose a more consistent interface. For example, the background color for HTMLControls may be managed by using a style attribute in some cases, and by using a property in other cases. WebControls always expose the background color of the control through the BackColor property.
      Declaring WebControls on a page is a little different from declaring HTMLControls. Take a look at Figure 7, which shows the Axe 'n' Stacks page source code using ASP .NET WebControls. Notice the selection control is declared as an asp:DropDownList and the contents are declared using the asp:ListItem control. Likewise, rather than declaring a normal button, Figure 7 declares an asp:Button tag. The images are managed by asp:Image controls, and the textual information is shown in an asp:TextBox control. If you take a look at the handler near the top of the code, you'll see that some of the field names used to manage the data in the controls have changed. For example, instead of accessing the selection, the HTMLSelect's Value property (as shown in Figure 5), accesses the DropDownList's SelectedItem.Text property. Otherwise, the program structure is basically the same as the one using HTMLControls.

Complex Controls

      WebControls have an advantage over HTMLControls in that they offer a more consistent interface. In addition, the WebControls include several other more complex controls that are useful on a Web page. These include the AdRotator, the Calendar, and the DataGrid controls. The AdRotator control accepts a list of images (GIF files or JPEG files, for example) mapped to a specific URL (to surf to in response to clicking on the ad). The AdRotator control randomly selects an image each time the page is refreshed. The Calendar control displays a fully working calendar on the browser, and the DataGrid control behaves like a mini-spreadsheet. I'll look at some of these controls in depth in a later column.

Conclusion

      At the end of the day, Web development is all about receiving HTTP requests and responding to them. Sometimes the response to an HTTP request requires pushing control tags out to the browser. When programming straight ASP, you often spend a good deal of coding time and sweat getting the controls to behave consistently. Remember, it's not a desktop-app world anymore. Your applications are going to be hit by lots of different clients all the time. ASP .NET controls manage much of the work for you so you can feel almost as though you're programming in MFC or Visual Basic®, even though your application (and user interface) may be distributed across the globe.

Send questions and comments for George to asp-net@microsoft.com.

*We've extended last month's search for naming The ASP Column. While we did receive some interesting suggestions (some can't be printed in this respectable publication), we still haven't come across the perfect one. Send your suggestions to asp-net@microsoft.com with "column name" in the subject line by September 15. If your suggestion is selected, we'll send you an MSDN Magazine mug and T-shirt.
George Shepherd is an associate technology director at Plural where he helps companies use Microsoft technologies effectively. In addition, George delivers seminars with DevelopMentor and is the coauthor of an upcoming book,
Applied .NET from Addison-Wesley.

From the September 2001 issue of MSDN Magazine.