- ASP.NET and the .NET Framework
- Understanding ASP.NET Controls
- Understanding ASP.NET Pages
- Installing the ASP.NET Framework
- Summary
Understanding ASP.NET Controls
ASP.NET controls are the heart of the ASP.NET Framework. An ASP.NET control is a .NET class that executes on the server and renders certain content to the browser.
For example, in the first ASP.NET page created at the beginning of this chapter, a Label control was used to display the current date and time. The ASP.NET framework includes over 70 controls, which enable you to do everything from displaying a list of database records to displaying a randomly rotating banner advertisement.
In this section, you are provided with an overview of the controls included in the ASP.NET Framework. You also learn how to handle events that are raised by controls and how to take advantage of View State.
Overview of ASP.NET Controls
The ASP.NET Framework contains over 70 controls. These controls can be divided into eight groups:
- Standard Controls—The standard controls enable you to render standard form elements such as buttons, input fields, and labels. We examine these controls in detail in the following chapter, "Using the Standard Controls."
- Validation Controls—The validation controls enable you to validate form data before you submit the data to the server. For example, you can use a RequiredFieldValidator control to check whether a user entered a value for a required input field. These controls are discussed in Chapter 3, "Using the Validation Controls."
- Rich Controls—The rich controls enable you to render things such as calendars, file upload buttons, rotating banner advertisements, and multi-step wizards. These controls are discussed in Chapter 4, "Using the Rich Controls."
- Data Controls—The data controls enable you to work with data such as database data. For example, you can use these controls to submit new records to a database table or display a list of database records. These controls are discussed in detail in Part III of this book, "Performing Data Access."
- Navigation Controls—The navigation controls enable you to display standard navigation elements such as menus, tree views, and bread crumb trails. These controls are discussed in Chapter 19, "Using the Navigation Controls."
- Login Controls—The login controls enable you to display login, change password, and registration forms. These controls are discussed in Chapter 22, "Using the Login Controls."
- HTML Controls—The HTML controls enable you to convert any HTML tag into a server-side control. We discuss this group of controls in the next section of this chapter.
With the exception of the HTML controls, you declare and use all the ASP.NET controls in a page in exactly the same way. For example, if you want to display a text input field in a page, then you can declare a TextBox control like this:
<asp:TextBox id="TextBox1" runat="Server" />
This control declaration looks like the declaration for an HTML tag. Remember, however, unlike an HTML tag, a control is a .NET class that executes on the server and not in the web browser.
When the TextBox control is rendered to the browser, it renders the following content:
<input name="TextBox1" type="text" id="TextBox1" />
The first part of the control declaration, the asp: prefix, indicates the namespace for the control. All the standard ASP.NET controls are contained in the System.Web.UI.WebControls namespace. The prefix asp: represents this namespace.
Next, the declaration contains the name of the control being declared. In this case, a TextBox control is being declared.
This declaration also includes an ID attribute. You use the ID to refer to the control in the page within your code. Every control must have a unique ID.
The declaration also includes a runat="Server" attribute. This attribute marks the tag as representing a server-side control. If you neglect to include this attribute, then the TextBox tag would be passed, without being executed, to the browser. The browser would simply ignore the tag.
Finally, notice that the tag ends with a forward slash. The forward slash is shorthand for creating a closing </asp:TextBox> tag. You can, if you prefer, declare the TextBox control like this:
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
In this case, the opening tag does not contain a forward slash and an explicit closing tag is included.
Understanding HTML Controls
You declare HTML controls in a different way than you declare standard ASP.NET controls. The ASP.NET Framework enables you to take any HTML tag (real or imaginary) and add a runat="server" attribute to the tag. The runat="server" attribute converts the HTML tag into a server-side ASP.NET control.
For example, the page in Listing 1.5 contains a <span> tag, which has been converted into an ASP.NET control.
Listing 1.5. HtmlControls.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> void Page_Load() { spanNow.InnerText = DateTime.Now.ToString("T"); } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>HTML Controls</title> </head> <body> <form id="form1" runat="server"> <div> At the tone, the time will be: <span id="spanNow" runat="server" /> </div> </form> </body> </html>
Notice that the <span> tag in Listing 1.5 looks just like a normal HTML <span> tag except for the addition of the runat="server" attribute.
Because the <span> tag in Listing 1.5 is a server-side HTML control, you can program against it. In Listing 1.5, the current date and time are assigned to the <span> tag in the Page_Load() method.
The HTML controls are included in the ASP.NET Framework to make it easier to convert existing HTML pages to use the ASP.NET Framework. I rarely use the HTML controls in this book because, in general, the standard ASP.NET controls provide all the same functionality and more.
Understanding and Handling Control Events
The majority of the ASP.NET controls support one or more events. For example, the ASP.NET Button control supports the Click event. The Click event is raised on the server after you click the button rendered by the Button control in the browser.
The page in Listing 1.6 illustrates how you can write code that executes when a user clicks the button rendered by the Button control (in other words, it illustrates how you can create a Click event handler).
Listing 1.6. ShowButtonClick.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void btnSubmit_Click(object sender, EventArgs e) { Label1.Text = "Thanks!"; } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show Button Click</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button id="btnSubmit" Text="Click Here" OnClick="btnSubmit_Click" Runat="server" /> <br /><br /> <asp:Label id="Label1" Runat="server" /> </div> </form> </body> </html>
Notice that the Button control in Listing 1.6 includes an OnClick attribute. This attribute points to a subroutine named btnSubmit_Click(). The btnSubmit_Click() subroutine is the handler for the Button Click event. This subroutine executes whenever you click the button (see Figure 1.5).
Figure 1.5 Raising a Click event.
You can add an event handler automatically to a control in multiple ways when using Visual Web Developer. In Source view, add a handler by selecting a control from the top-left drop-down list and selecting an event from the top-right drop-down list. The event handler code is added to the page automatically (see Figure 1.6).
Figure 1.6 Adding an event handler from Source view.
In Design view, you can double-click a control to add a handler for the control's default event. Double-clicking a control switches you to Source view and adds the event handler.
Finally, from Design view, after selecting a control on the designer surface you can add an event handler from the Properties window by clicking the Events button (the lightning bolt) and double-clicking next to the name of any of the events (see Figure 1.7).
Figure 1.7 Adding an event handler from the Properties window.
It is important to understand that all ASP.NET control events happen on the server. For example, the Click event is not raised when you actually click a button. The Click event is not raised until the page containing the Button control is posted back to the server.
The ASP.NET Framework is a server-side web application framework. The .NET Framework code that you write executes on the server and not within the web browser. From the perspective of ASP.NET, nothing happens until the page is posted back to the server and can execute within the context of the .NET Framework.
Notice that two parameters are passed to the btnSubmit_Click() handler in Listing 1.6. All event handlers for ASP.NET controls have the same general signature.
The first parameter, the object parameter named sender, represents the control that raised the event. In other words, it represents the Button control which you clicked.
You can wire multiple controls in a page to the same event handler and use this first parameter to determine the particular control that raised the event. For example, the page in Listing 1.7 includes two Button controls. When you click either Button control, the text displayed by the Button control is updated (see Figure 1.8).
Figure 1.8 Handling two Button controls with one event handler.
Listing 1.7. ButtonCounters.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void Button_Click(object sender, EventArgs e) { Button btn = (Button)sender; btn.Text = (Int32.Parse(btn.Text) + 1).ToString(); } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Button Counters</title> </head> <body> <form id="form1" runat="server"> <div> First Counter: <asp:Button id="Button1" Text="0" OnClick="Button_Click" Runat="server" /> <br /><br /> Second Counter: <asp:Button id="Button2" Text="0" OnClick="Button_Click" Runat="server" /> </div> </form> </body> </html>
The second parameter passed to the Click event handler, the EventArgs parameter named e, represents any additional event information associated with the event. No additional event information is associated with clicking a button, so this second parameter does not represent anything useful in either Listing 1.6 or Listing 1.7.
When you click an ImageButton control instead of a Button control, on the other hand, additional event information is passed to the event handler. When you click an ImageButton control, the X and Y coordinates of where you clicked are passed to the handler.
The page in Listing 1.8 contains an ImageButton control that displays a picture. When you click the picture, the X and Y coordinates of the spot you clicked are displayed in a Label control (see Figure 1.9).
Figure 1.9 Clicking an ImageButton.
Listing 1.8. ShowEventArgs.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void btnElephant_Click(object sender, ImageClickEventArgs e) { lblX.Text = e.X.ToString(); lblY.Text = e.Y.ToString(); } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show EventArgs</title> </head> <body> <form id="form1" runat="server"> <div> <asp:ImageButton id="btnElephant" ImageUrl="Elephant.jpg" Runat="server" OnClick="btnElephant_Click" /> <br /> X Coordinate: <asp:Label id="lblX" Runat="server" /> <br /> Y Coordinate: <asp:Label id="lblY" Runat="server" /> </div> </form> </body> </html>
Notice that the second parameter passed to the btnElephant_Click() method is an ImageClickEventArgs parameter. Whenever the second parameter is not the default EventArgs parameter, you know that additional event information is being passed to the handler.
Understanding View State
The HTTP protocol, the fundamental protocol of the World Wide Web, is a stateless protocol. Each time you request a web page from a website, from the website's perspective, you are a completely new person.
The ASP.NET Framework, however, manages to transcend this limitation of the HTTP protocol. For example, if you assign a value to a Label control's Text property, the Label control retains this value across multiple page requests.
Consider the page in Listing 1.9. This page contains a Button control and a Label control. Each time you click the Button control, the value displayed by the Label control is incremented by 1 (see Figure 1.10). How does the Label control preserve its value across postbacks to the web server?
Figure 1.10 Preserving state between postbacks.
Listing 1.9. ShowViewState.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void btnAdd_Click(object sender, EventArgs e) { lblCounter.Text = (Int32.Parse(lblCounter.Text) + 1).ToString(); } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show View State</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button id="btnAdd" Text="Add" OnClick="btnAdd_Click" Runat="server" /> <asp:Label id="lblCounter" Text="0" Runat="server" /> </div> </form> </body> </html>
The ASP.NET Framework uses a trick called View State. If you open the page in Listing 1.9 in your browser and select View Source, you'll notice that the page includes a hidden form field named __VIEWSTATE that looks like this:
<input type="hidden" name="__VIEWSTATE" id="__ VIEWSTATE" value="/wEPDwUKLTc2ODE1OTYxNw9kFgICBA9kFgIC Aw8PFgIeBFRleHQFATFkZGT3tMnThg9KZpGak55p367vfInj1w==" />
This hidden form field contains the value of the Label control's Text property (and the values of any other control properties that are stored in View State). When the page is posted back to the server, the ASP.NET Framework rips apart this string and re-creates the values of all the properties stored in View State. In this way, the ASP.NET Framework preserves the state of control properties across postbacks to the web server.
By default, View State is enabled for every control in the ASP.NET Framework. If you change the background color of a Calendar control, the new background color is remembered across postbacks. If you change the selected item in a DropDownList, the selected item is remembered across postbacks. The values of these properties are automatically stored in View State.
View State is a good thing, but sometimes it can be too much of a good thing. The __VIEWSTATE hidden form field can become very large. Stuffing too much data into View State can slow down the rendering of a page because the contents of the hidden field must be pushed back and forth between the web server and web browser.
You can determine how much View State each control contained in a page is consuming by enabling tracing for a page (see Figure 1.11). The page in Listing 1.10 includes a Trace="true" attribute in its <%@ Page %> directive, which enables tracing.
Figure 1.11 Viewing View State size for each control.
Listing 1.10. ShowTrace.aspx
<%@ Page Language="C#" Trace="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> void Page_Load() { Label1.Text = "Hello World!"; Calendar1.TodaysDate = DateTime.Now; } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show Trace</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="Label1" Runat="server" /> <asp:Calendar id="Calendar1" TodayDayStyle-BackColor="Yellow" Runat="server" /> </div> </form> </body> </html>
When you open the page in Listing 1.10, additional information about the page is appended to the bottom of the page. The Control Tree section displays the amount of View State used by each ASP.NET control contained in the page.
Every ASP.NET control includes a property named EnableViewState. If you set this property to the value False, then View State is disabled for the control. In that case, the values of the control properties are not remembered across postbacks to the server.
For example, the page in Listing 1.11 contains two Label controls and a Button control. The first Label has View State disabled and the second Label has View State enabled. When you click the button, only the value of the second Label control is incremented past 1.
Listing 1.11. DisableViewState.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void btnAdd_Click(object sender, EventArgs e) { Label1.Text = (Int32.Parse(Label1.Text) + 1).ToString(); Label2.Text = (Int32.Parse(Label2.Text) + 1).ToString(); } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Disable View State</title> </head> <body> <form id="form1" runat="server"> <div> Label 1: <asp:Label id="Label1" EnableViewState="false" Text="0" Runat="server" /> <br /> Label 2: <asp:Label id="Label2" Text="0" Runat="server" /> <br /><br /> <asp:Button id="btnAdd" Text="Add" OnClick="btnAdd_Click" Runat="server" /> </div> </form> </body> </html>
Sometimes, you might want to disable View State even when you aren't concerned with the size of the __VIEWSTATE hidden form field. For example, if you are using a Label control to display a form validation error message, you might want to start from scratch each time the page is submitted. In that case, simply disable View State for the Label control.