Introducing ASP.NET Controls
ASP.NET controls provide the dynamic and interactive portions of the user interface for your Web application. The controls render the content that the users of your Web site actually see and interact with. For example, you can use controls to create HTML form elements, interactive calendars, and rotating banner advertisements.
ASP.NET controls coexist peacefully with HTML content. Typically, you create the static areas of your Web pages with normal HTML content and create the dynamic or interactive portions with ASP.NET controls.
The best way to understand how ASP.NET controls work in an HTML page is to look at a simple Web Forms Page.
A Simple ASP.NET Page
Let's start by looking at a normal, everyday HTML page. You'll convert this page into an ASP.NET page in a moment. First, open Notepad on your computer and enter the HTML page contained in Listing 1. After you finish entering the HTML page into Notepad, save it with the name SimpleHTML.aspx in your inetpub/wwwroot directory.
When you create ASP.NET pages, be sure to save them in a directory that your Web server can access. You need to save your pages in the inetpub/wwwroot directory, a subdirectory of the inetpub/wwwroot directory, or within a virtual directory of your Web server.
After you save a page, do not open the page directly in your Web browser by typing the file path of the page. If your Web server is located on the same computer as your Web browser, open the page by entering the page's address in the Address Bar of your browser. For example, if the page is named simpleHTML.aspx, open the page by typing the following text into your browser's Address Bar:
For purposes of this book, I'll assume that you are using Notepad to create your Web pages. However, there is nothing wrong with using other text editors or Web development environments such as Microsoft Visual Studio.NET, Microsoft Visual Interdev, Allaire's Homesite, or TextPad. Any program that can save a file as plain text will work fine.
When you're saving a file with Notepad, remember to pick All Types as the value in the Save as Type box in the Save As dialog box. If you don't choose this option, Notepad automatically adds the extension .txt to the name of your file. An alternative method of preventing .txt from being appended to your filename is to place the filename in quotation marks when saving the file.
<html> <head><title>Simple HTML Page</title></head> <body> <form method="post" action="SimpleHTML.aspx"> <b>Username:</b> <br><input name="username" type="text" size="30"> <p> <b>Comments:</b> <br><textarea name="comments" cols=60 rows=10></textarea> <p> <input type="submit" value="Add Comment"> </form> </body> </html>
The page in Listing 1 contains a simple HTML form that includes a text field for a username and a text area for comments. This form might be used, for example, in a simple guest book application at a Web site. You might notice that the HTML form posts back to itself (the ACTION attribute of the <form> tag submits the form data to SimpleHTML.aspx). So, when the Add Comment button is clicked, the same form appears once again.
The HTML form in Listing 1 doesn't contain any ASP.NET controls. Now, open the page in a Web browser (Microsoft Internet Explorer or Netscape Navigator); then try entering a username and some comments and submitting the form. Notice that the data you enter into the form fields disappears every time you submit the form.
Now modify the page in Listing 1 so that it uses ASP.NET controls rather than the standard HTML form elements. You're going to convert the form fields into "smart" server-side form fields. Enter the page contained in Listing 2, and save the file with the name SimpleASPX.aspx in a directory that your Web server can access.
<html> <head><title>Simple ASPX Page</title></head> <body> <form Runat="Server"> <b>Username:</b> <br><input id="username" type="text" size="30" Runat="Server"> <p> <b>Comments:</b> <br><textarea id="comments" cols=60 rows=10 Runat="Server"></textarea> <p> <input type="submit" value="Add Comment" Runat="Server"> </form> </body> </html>
Notice the four modifications to this page. First, you rename the page from SimpleHTML.aspx to SimpleASPX.aspx. The particular name of the file is not important, but the .aspx extension is very important. Your Web server detects that the page is an ASP.NET page and not a normal HTML page or other type of page because of the special .aspx extension. You create all your ASP.NET pages with this special extension.
ASP Classic Note
What about files that end with the extension .asp? Classic ASP developers (users of versions of ASP before ASP.NET) named all their ASP files with the extension .asp instead of .aspx. You can continue to name your ASP files with the extension .asp, but they do not gain any of the new functionality of ASP.NET. Files with the .asp extension continue to be executed as classic ASP files.
By default, files with the extension .asp are mapped by Internet Information Server (IIS) to asp.dll, and files with the extension .aspx are mapped to aspnet_eisapi.dll. So, both classic ASP files and ASP.NET files can happily live and work together on the same Web server.
You might want to use an extension other than .aspx for your ASP.NET pages in several situations. For example, you might have a Web site with hundreds of existing pages with names that end with the extension .htm or .html and that have already been indexed by a search engine such as AltaVista or Google. You might not want to change the extensions of these filenames because you fear that you'll lose ranking in the search engines.
You can, in fact, use any extension that you please for ASP.NET pages. See the first appendix at the back of this book, Migrating from ASP to ASP.NET, for details on how to do this.
Second, notice that the attribute Runat="Server" is added to all the form tags. For example, instead of using
<input name="username" type="text" size="30">
to create the username form field, you use the following tag instead:
<input id="username" type="text" size="30" Runat="Server">
The Runat="Server" attribute converts these standard HTML tags into "smart" server-side HTML tags. When the SimpleASX.aspx page is opened in a Web browser, the form tags with this attribute are executed on the Web server before any content is rendered to the Web browser. The Runat="Server" attribute converts these standard HTML tags into ASP.NET controls.
Third, notice that instead of using the NAME attribute to name the form fields, you give the form fields a unique identifier with the ID attribute. You use the ID attribute because you are no longer treating the form fields as simple HTML tags; you are converting the form fields into server-side objects.
Finally, notice that you modify Listing 1 so that you can open the HTML form using
rather than the standard
<form method="post" action="SimpleASPX.aspx">
If you want to convert any of the form fields within an HTML form into ASP.NET controls, you must use the Runat="Server" attribute with the opening form tag.
Notice that the Method attribute of the form tag is not used with the control version of the form tag. By default, the ASP.NET HTML Form control automatically includes this attribute.
By default, the standard HTML form tag's Method attribute has the value GET. When a form is submitted with the Method="Get" attribute, the form data is submitted as query string variables. Because a lot of form data cannot be passed in a query string (it's browser-dependent, but typically not more than 1,000 to 2,000 characters), most people add a Method="POST" to the form tag whenever they create an HTML form.
The ASP.NET version of the form tag has the opposite behavior. By default, form data is posted with Method="POST". This version is nice because it saves some typing (I've spent the past six years typing Method="POST" whenever I create a form). If you really want to, however, you can override this behavior and specify Method="Get".
Furthermore, notice that an Action attribute is not specified. The ASP.NET HTML Form control automatically posts back to the same page (SimpleASPX.aspx). Therefore, the server-side version of the form tag performs the same way as the original form tag, but with less typing on your part.
In short, to convert a standard HTML file into an ASP.NET page, you make four modifications to the page:
You rename the file so that the filename ends with the extension .aspx.
You add the attribute Runat="Server" to each of the form tags.
Instead of using the NAME attribute for the form tags, you use ID instead.
You convert the opening <form> tag from <form method="post" action="SimpleASPX.aspx"> to the simpler <form Runat="Server">.
Now that you've converted a standard HTML form into a "smart" ASP.NET form, what do you get out of it? Open the page in Listing 2 (SimpleASPX.aspx) in a Web browser and try submitting the form. Notice that all the form data (any text you type into the username and comments fields) is preserved between form posts. Now try to post the form over and over again. Notice that the form data does not disappear.
Whenever I demonstrate a smart ASP.NET form to people, I always receive what I call the Yawn Reaction. "Okay," a typical response goes, "the form saves the data, but what's the big deal?" Users of earlier versions of ASP inevitably respond, "I could do the same thing with a couple lines of script in any case."
In the next section, I try to convince you that something interesting is, in fact, happening here. The ASP.NET page contained in Listing 2 is doing a lot of complicated work in the background that opens up several exciting programming possibilities.
Benefits of ASP.NET Controls
In the preceding section, you took a standard HTML form and converted it into a smart ASP.NET form. You did so by converting all the form tags into server-side HTML tags. Why bother? Why use ASP.NET controls at all? Using these controls provides four important benefits:
ASP.NET controls expose the HTML elements of a page in an intuitive object model.
ASP.NET controls automatically retain the value of their properties by participating in view state.
ASP.NET controls enable you to cleanly separate the design content of a page from the application logic.
You look in more detail at each of these benefits of ASP.NET controls in the following sections.
An Intuitive Object Model
Normally, a Web server ignores the HTML tags in a page. From a Web server's perspective, these tags are just meaningless strings of text sent to a Web browser. It's the browser and not the server that performs all the hard work of parsing the tags in a Web page and displaying <b>bold</b> as bold.
However, after an HTML tag is converted into an ASP.NET control, the tag is no longer a meaningless string of text to the Web server. The tag has become a server-side object with properties, methods, collections, and events that you can program against.
Converting standard HTML tags into server-side objects opens up many programming possibilities. After the HTML elements of a page have been exposed as server-side objects, you can manipulate the properties of the objects through server-side code. You can write application logic that reads or modifies the properties of the objects. You can even programmatically add new objects to a page or hide existing ones.
For example, after the username form field has been converted into an ASP.NET control, you can set and read the username control's Value property. The Value property determines the text that is displayed by the control. You can write application logic that assigns any value to the username control that you please. Or you can write code that reads the Value property and saves it to a file or database.
Listing 3 contains a form that has two fields (labeled field1 and field2). If you enter text into the first form field and click the submit button, the text is copied to the second field. Now try the page (it's included on the CD with the name CopyField.aspx).
<Script Runat="Server"> Sub Button_Click( s As Object, e As EventArgs ) field2.Value = field1.Value End Sub </Script> <html> <head><title>CopyField.aspx</title></head> <body> <form Runat="Server"> <b>Field 1:</b> <br><input id="field1" size="30" Runat="Server"> <p> <b>Field 2:</b> <br><input id="field2" size="30" Runat="Server"> <p> <input type="submit" OnServerClick="Button_Click" Runat="Server"> </form> </body> </html>
The text is copied from the first field to the second with the following line of code:
field2.Value = field1.Value
This statement assigns the Value property of field1 to the Value property of field2. Notice how intuitive the code is. By exposing the elements of an HTML page as server-side objects, you gain control over all the properties of a page in an easy-to-understand manner.
Also notice how controls enable you to use an event-driven programming model. Clicking the submit button raises the Click event and the Button_Click subroutine executes. In classic Active Server Pages, you could only write pages that execute from top to bottom. ASP.NET, on the other hand, enables you to write code that executes in response to events raised by particular user actions. Once again, this is a much more intuitive programming model.
As you saw in the preceding section, when you submit a form built from ASP.NET controls, the data entered into all the form fields is preserved when the form is displayed again. Microsoft calls this automatic persistence of data view state. ASP.NET controls automatically preserve view state.
When you started with the simple HTML form, you did not get any of the benefits of view state. With a standard HTML form, you don't notice any difference between the first time the form is submitted and the seventh time; you must start over with empty form fields every time.
Note that view state does not apply only to the ASP.NET controls that correspond to form elements; all the standard ASP.NET controls preserve their state. For example, you can take a standard HTML <span> tag and make it into an ASP.NET control like this:
<span id="myLabel" Runat="Server">
In this line, you magically convert the <span> tag into an ASP.NET control by adding an ID attribute and a Runat="Server" attribute. Now that the <span> tag is a server-side control, any text assigned to it is preserved every time a Web Forms Page that contains the tag is posted back to itself. This is illustrated in the page contained in Listing 4.
<Script Runat="Server"> Sub Button_Click( s As Object, e As EventArgs ) entries.innerHtml = "<hr>" & username.Value & "<p>" & comments.Value & entries.innerHTML End Sub </Script> <html> <head><title>Guestbook.aspx</title></head> <body> <form Runat="Server"> <b>Username:</b> <br><input id="username" type="text" size="30" Runat="Server"> <p> <b>Comments:</b> <br><textarea id="comments" cols=60 rows=10 Runat="Server"></textarea> <p> <input type="submit" value="Add Comment" OnServerClick="Button_Click" Runat="Server"> <span id="entries" Runat="Server" /> </form> </body> </html>
The page in Listing 4 contains the same guest book form as in Listing 2. Like the form in Listing 2, the text entered into the username and comments form fields is preserved whenever the form is submitted. The view state of the username and comments controls is automatically preserved.
Furthermore, you should notice that all the previous entries into the guest book are also preserved at the bottom of the form (see Figure 1). These entries are stored in the <span> tag's view state. (The <span> tag with the entries ID.) Every time the form is posted, the contents of the Username and Comments fields are added to the <span> tag's view state.
Figure 1 Preserving view state.
The contents of the Username and Comments fields are added to the text displayed by the <span> tag by modifying the <span> tag's innerHTML property. Every time a new guest book entry is added, the following code is executed:
entries.innerHTML = "<hr>" & username.Value & "<p>" & comments.Value & entries.innerHTML
How is the view state of the <span> tag preserved? When you look at the source of the HTML page (in Microsoft Internet Explorer, select View, Source, or in Netscape Navigator, select View, Page Source), you notice a hidden form field that looks something like this:
<input type="hidden" name="__VIEWSTATE" value="YTB6LTU2MjIwODU1X2Ewel9oejV6MX hfYTB6X2h6NXo3eF9hMHpoejBfPGhyPkJvYlxxRnJlZDxwPkhlcmUgaXMgbXkgY29tbWV udCANCmFuZCA8aHI+Qm9iPHA+SGVyZSBpcyBteSBjb21tZW50PGhyPlN0ZXZlPHA+SGVy ZSBpcyBteSBjb21tZW50PGhyPlN0ZXZlPHA+SGVyZSBpcyBteSBjb21tZW50PGhyPlN0ZX ZlPHA+SGVyZSBpcyBteSBjb21tZW50eF9feF81ejN4X2Ewemh6MF9IZXJlIGlzIG15IGNv bW1lbnQgDQphbmQgeF9feHhfeHhfeF9feFxuMF9pbm5lcmh0bWw=a6f9326a" />
This long, ugly hidden form field contains all the previous entries in the guest book. The view state of all the controls contained in a Web Forms Page is preserved in the hidden form field named __VIEWSTATE.
View state is preserved only if a form is posted back to itself. If you leave the Guestbook.aspx page and visit the Yahoo home page and return again, the view state of Guestbook.aspx is lost (and all the guest book entries disappear into the ether). Or, if a form posts to another page, all the view state information also is lost.
Why is view state useful? One situation in which view state is important is form validation. Suppose that you create a user registration form and the form has several required form fields. For example, you don't want anyone to be able to submit the form without entering a first and last name.
Now imagine that someone submits the user registration form without completing the required form fields. In this situation, you want to display an appropriate error message. Furthermore, you want to redisplay all the form information that the user has already entered. Making the user start over from scratch every time a problem occurs with the data the user submitted is not a very nice thing to do. View state, as you have seen, automatically preserves the form information that the user previously entered.
Separating Code from Content
Good programmers are not necessarily good designers. Most companies divide the task of developing a Web site between a design team and an engineering team. The design team is responsible for making a Web site pretty; the engineering team is responsible for making the Web site work.
This division of labor was difficult to carry out with previous versions of Active Server Pages. The problem was that there was no clean way to separate the application logic of a Web page from its design elements. Designers had a tendency to mess up programming code. Engineers had no easy way to integrate design elements. The code and content were jumbled together in the same page.
ASP.NET controls provide you with a clean method of dividing the code (application logic) from the content (design elements of the page). Designers can place ASP.NET controls into a page without worrying about the application logic. They can concentrate on layout and graphics. After the page is designed, it can be handed off to the engineering team. The application logic can be added to a separate section of the page or, better yet, to a separate file.
Designers can even piece together an ASP.NET page using a visual development environment such as Visual Studio. You can drag and drop ASP.NET controls from a toolbar and quickly create a complicated page. Using a tool such as Visual Studio, you can design ASP.NET pages in the same way that Visual Basic or Visual C++ programmers have traditionally created complicated Windows forms.
ASP.NET pages are executed on the server, not on the browser. When a browser requests an ASP.NET page, a standard HTML page is retrieved. This means that an ASP.NET page can be made to be compatible with any browser.
Overview of ASP.NET Controls
You can add more than 50 standard ASP.NET controls to your Web Forms Pages. These controls can be divided into two types: HTML controls and Web controls. The next two sections provide an overview of each type of control. To view a complete reference on the properties and methods of each control, see Appendix B, "HTML Control Reference," and Appendix C, "Web Control Reference."
ASP.NET HTML Controls
You've already seen some examples of the HTML controls in earlier sections of this article. The HTML controls are server-side replicas of the standard HTML tags.
Corresponding to the standard HTML text <input> tag, for example, is the HTMLInputText control:
<input id="username" type="text" size="30" Runat="Server">
And corresponding to the standard HTML <img> tag is the HTMLImage control:
<img ID="myImage" src="smile.gif" Runat="Server">
You get the idea. For each of the most common HTML tags, a server-side HTML control corresponds to it. Just stick a Runat="Server" attribute on the end of the tag, and you have created the HTML control version of it. Furthermore, any HTML tags that are not represented by a distinct server control can be represented with the HtmlGenericControl. You can use the HTML controls to quickly convert any existing HTML document into a "smart" ASP.NET Web Forms Page. The following sections provide a complete list of the ASP.NET HTML controls.
The HTML controls can represent any HTML tag through the HtmlGenericControl control. This means that if new HTML tags are introduced with a future version of HTML, you still can represent the new tags with HtmlGenericControl. You can even use HTMLGenericControl to represent a tag that you make up yourselffor example, the <MyOwnTag> tag. There is nothing wrong with creating a server-side tag like this:
You might be curious about how the HTML controls handle new or obscure HTML attributes. For example, suppose that you add an attribute called myAttribute to the standard HtmlInputText control like this:
<input id="username" type="text" myAttribute="39" Runat="Server">
This attribute does not cause an error. If you add a strange attribute to an HTML control, the control simply passes the attribute with its value unaltered to the Web browser when the control is rendered. This guarantees that the HTML controls remain compatible with future versions of HTML.
HtmlAnchor creates a server-side HTML anchor tag, as shown in this example:
<a href="somepage.aspx" Runat="Server">Click Here</a>
HtmlButton creates a server-side HTML 4.0 button tag. Don't confuse the HtmlButton control with the HTMLInputButton control used for creating form buttons. The HtmlButton control renders an HTML 4.0compliant <button> tag, as shown here:
<button Runat="Server">Click Here</button>
HtmlForm creates a server-side HTML <form> tag. You must use this control, as shown here, if you want to include other ASP.NET controls in the Web Forms Page:
HtmlGenericControl creates a server-side control for HTML tags that do not have an HTML control that directly corresponds to them. For example, if you use a <span>, <body>, or <marquee> tag with the Runat="Server" attribute, as shown here, an instance of the HTMLGenericControl is created:
<span Runat="Server">Hello World!</span>
HtmlImage creates a server-side <img> tag, as in this example:
<img ID="myImage" src="smile.gif" Runat="Server">
HtmlInputButton creates a server-side <input type="submit">, <input type="reset">, or <input type="button"> tag, as in this example:
<input type="Submit" value="Click Here!" Runat="Server">
HtmlInputCheckBox creates a server-side <input type="checkbox"> tag, as in this example:
<input type="checkbox" Runat="Server"> Do you like this Web Site?
HtmlInputFile creates a server-side <input type="file"> tag used for accepting file uploads, as in this example:
<input type="file" Runat="Server">
HtmlInputHidden creates a server-side <input type="hidden"> tag, as in this example:
<input type="hidden" Runat="Server">
HtmlInputImage creates a server-side <input type="image"> tag, as in this example:
<input type="image" Runat="Server">
HtmlInputRadioButton creates a server-side form radio button, as in this example:
Gender? <br> <input type="radio" Runat="Server"> Male <br> <input type="radio" Runat="Server"> Female
HtmlInputText creates a server-side <input type="text"> or <input type="password"> tag, as in this example:
Please Login: Username: <input id="username" type="text" Runat="Server"> <p> Password: <input id="password" type="password" Runat="Server">
HtmlSelect creates a server-side version of the HTML <select> tag for creating drop-down lists or list boxes, as in this example:
Select your favorite movie: <Select Runat="Server"> <option>Star Wars</option> <option>Citizen Kane</option> <option>The Princess Bride</option> </Select>
HtmlTable creates a server-side version of the HTML <table> tag for creating HTML tables, as in this example:
<table border=1 cellspacing=0 cellpadding=4 Runat="Server">
HtmlTableCell creates a server-side version of the HTML table <td> tag for creating table cells, as in this example:
<td Runat="Server"> Table Data </td>
HtmlTableRow creates a server-side version of the HTML table <tr> tag for creating table rows, as in this example:
<tr Runat="Server"> <td Runat="Server"> Table Data 1 </td> <td Runat="Server"> Table Data 2 </td> </tr>
HtmlTextArea creates a server-side version of the form <textArea> tag for creating multiline text input fields, as in this example:
<textarea cols="60" rows="10" Runat="Server"></textarea>
When you create an ASP.NET page with ASP.NET controls, you have a choice. Either you can use the HTML controls discussed in the previous sections to build the page, or you can use the Web controls. All the most common HTML tags can be represented equally well with either an HTML control or a Web control.
The HTML controls are all contained in the System.Web.UI.HTMLControls namespace, and the Web controls are contained in the System.Web.UI.WebControls namespace.
Why are you given this choice? The HTML controls were designed to be server-side duplicates of the standard HTML tags so that you can quickly convert an existing HTML document into an ASP.NET page. The HTML controls mirror the standard HTML tags almost exactly. This is not true in the case of the Web controls.
Web controls are a more rationalized version of the standard HTML tags. Remember that the HTML standard has evolved slowly over time. Because the attributes of the standard HTML tags were cobbled together over time, they don't always make the most sense.
Consider the standard HTML <select> tag. You can use it to create a single-select drop-down list like this:
<select name="favColor"> <option> Red </option> <option> Blue </option> <option> Green </option> </select>
Alternatively, you can use the same tag to create a multiselect list box like this:
<select name="favColor" Size="3" MULTIPLE> <option> Red </option> <option> Blue </option> <option> Green </option> </select>
Being able to use the tags this way really doesn't make a lot of sense. When a browser renders the same tag with slightly different attributes, very different user interface elements are created (see Figure 2).
Figure 2 Difference between DropDownList and ListBox.
With the ASP.NET controls, Microsoft basically reinvented HTML starting from scratch. For example, it created two different Web controls that correspond to the two different versions of the <select> tag: a DropDownList control and ListBox control.
Because the Web controls do not directly correspond to standard HTML tags, you cannot create a Web control by simply sticking the Runat="Server" attribute at the end of a standard HTML tag. The Web controls do not look like standard HTML tags. For example, the Web control that corresponds to the standard HTML text <input> tag
<INPUT NAME="username" TYPE="text" SIZE="30">
<asp:TextBox id="username" Columns="30" Runat="Server"/>
However, if you place the TextBox Web control in an ASP.NET page, the standard HTML text <input> tag is rendered.
Microsoft fixed up standard HTML with the Web controls in one other place. Notice that the TextBox control is closed with a trailing forward slash (/). When you add a Web control to a page, you must be careful to always explicitly close the tag. You can close the TextBox control like this:
<asp:TextBox id="username" Columns="30" Runat="Server"></asp:TextBox>
Orthis approach requires less typingyou can close the TextBox control like this:
<asp:TextBox id="username" Columns="30" Runat="Server"/>
There are more Web controls than there are HTML controls. Several of the Web controls do not correspond to existing HTML tags at all. The Web controls can be divided into five different groups:
- Basic Web controls
- Validation Web controls
- Data controls
- Rich Web controls
- Mobile controls
The first group consists of the Web controls that (roughly) correspond to existing HTML tags. The Web controls in this group include the TextBox, DropDownList, and ListBox controls. You can use these controls instead of the HTML controls to create server-side versions of standard HTML tags. The Web controls are as follows:
The second group of Web controls contains controls used for form validation. For example, you can add Web controls to an HTML form to make certain fields in the form required. The controls in this group do not correspond to any existing HTML tags. The following list contains all the validation Web controls.
The third group of controls displays data. For example, you can use the DataGrid control to easily display data from a database table. The controls in this group are discussed in detail in the third part of this book, "Working with ADO.NET." The following is a complete list of the data-related Web controls.
Microsoft included a couple of more complicated controls with the ASP.NET Web controls. They include a control that can render an interactive calendar, the Calendar Web control, and a control for displaying banner advertisements, the AdRotator control.
Finally, Microsoft developed several controls for working with mobile devices such as cell phones and personal digital assistants (PDAs) such as the Microsoft Pocket PC. You can target these devices in your ASP.NET pages by using the Mobile controls. (There are too many to list here.)