September 18, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Programming Microsoft .NET : Web Forms

  • February 26, 2002
  • By Jeff Prosise
  • Send Email »
  • More Articles »

Your First Web Form

ASP is a fine solution for performing server-side processing of HTML form input and dynamically generating HTML, but despite its youth, ASP has already grown long in the tooth. What's wrong with ASP? For starters, it's slow. ASP scripts are interpreted rather than compiled, so you incur the cost of recompiling your scripts on each and every page access. Another problem is that ASP lacks a true encapsulation model. It's not possible, for example, to build reusable ASP controls that encapsulate complex rendering and behavioral logic.

Enter ASP.NET Web forms. Web forms bring object-oriented programming to the Web. They also combine ASP's ease of use with the speed of compiled code. Figure 5-6 holds the source code for the Web Forms version of Calc.asp. The .aspx filename extension identifies the file as an ASP.NET resource. Figure 5-7 shows how Calc.aspx appears in Internet Explorer. Here's how to run it on your PC:

  1. Copy Calc.aspx to your PC's \Inetpub\wwwroot directory.

  2. Start Internet Explorer or the browser of your choice and type http://localhost/calc.aspx in the browser's address bar. The Web form will appear in the browser window.

  3. Type 2 and 2 into the input fields and click the = button. The number 4 should appear to the right of the button.

The \Inetpub\wwwroot directory is an IIS virtual directory; it's created automatically when you install IIS. If you'd prefer not to clutter \Inetpub\wwwroot, you can set up virtual directories of your own using the Internet Services Manager applet found under Administrative Tools. You could, for example, put Calc.aspx in a directory named Samples and make Samples a virtual directory. If you assign the Samples directory the logical name "Samples" (virtual directory names don't have to equal physical directory names, although they often do), you'd run Calc by typing http://localhost/samples/calc.aspx in the browser's address bar. The same goes for other ASPX files presented in this chapter and throughout the remainder of the book.

Calc.aspx

<html>  <body>    <form runat="server">      <asp:TextBox ID="op1" RunAt="server" />      +      <asp:TextBox ID="op2" RunAt="server" />      <asp:Button Text="  =  " OnClick="OnAdd" RunAt="server" />      <asp:Label ID="Sum" RunAt="server" />    </form>  </body></html><script language="C#" runat="server">  void OnAdd (Object sender, EventArgs e)  {      int a = Convert.ToInt32 (op1.Text);      int b = Convert.ToInt32 (op2.Text);      Sum.Text = (a + b).ToString ();  }</script>
Figure 5-6. ASP.NET Web form calculator.


Figure 5-7. ASP.NET in action

Web forms are built from a combination of HTML and server controls. Calc.aspx contains four server controls: two TextBox controls, a Button control, and a Label control. TextBox, Button, and Label are classes defined in the System.Web.UI.WebControls namespace in the .NET Framework class library (FCL). Each time Calc.aspx is requested, ASP.NET instantiates TextBox, Button, and Label objects and asks each object to render itself into HTML. The HTML returned by the controls is included in the HTTP response. Execute a View/Source command while Calc.aspx is displayed in Internet Explorer and you'll see the following HTML:

<html>  <body>    <form name="_ctrl0" method="post" action="calc.aspx" id="_ctrl0">      <input type="hidden" name="__VIEWSTATE"         value="dDwxOTE0NDY4ODE2Ozs+" />      <input name="op1" type="text" id="op1" />      +      <input name="op2" type="text" id="op2" />      <input type="submit" name="_ctrl1" value="  =  " />      <span id="Sum">    </form>  </body></html>

The TextBox controls turned into <input type="text"> tags, the Button control turned into an <input type="submit"> tag, and the Label control turned into a <span> tag. In effect, these controls "project" a user interface to the browser by rendering themselves into HTML.

What about the hidden <input> field named __VIEWSTATE in the HTML returned by Calc.aspx? That's the mechanism ASP.NET uses to round-trip data from the server to the client and back to the server again. You'll learn all about it in Chapter 8.

Control Properties

Server controls do more than render HTML. They also implement methods, properties, and events that make them highly programmable. For example, TextBox, Button, and Label controls each expose text through a read/write property named Text. If you wanted "2" to appear in the TextBox controls by default, you could modify the control tags as follows:

<asp:TextBox Text="2" ID="op1" RunAt="server" /><asp:TextBox Text="2" ID="op2" RunAt="server" />

Any public property that a control implements can be initialized by using the property name as an attribute in the tag that declares the control.

Properties can also be accessed from server-side scripts. In Calc.aspx, the server-side script is the code that appears between the <script> and </script> tags. The statements

int a = Convert.ToInt32 (op1.Text);int b = Convert.ToInt32 (op2.Text);

extract user input from the TextBox controls by reading their Text properties, while the statement

Sum.Text = (a + b).ToString ();

displays the sum of the inputs by writing to the Label control's Text property. The names op1, op2, and Sum are the controls' programmatic IDs. Control IDs are defined by including ID attributes in control tags. In Calc.aspx, the Label control serves as a placeholder for the Web form's output. Because the default value of a Label control's Text property is an empty string, nothing appears in the form where the Label control is positioned until the server-side script assigns a string to the Label control's Text property.

Control Events

The ability to encapsulate complex rendering and behavioral logic in reusable control classes is one of the fundamental tenets of the Web Forms programming model. Another is events and event handling. Most server controls fire events in response to user input. Button controls, for example, fire Click events when they're clicked. Wiring an event to an event handler is accomplished by prefixing the event name with "On" and using the resulting text as an attribute in the tag that declares the control. In Calc.aspx, the statement

<asp:Button Text="  =  " OnClick="OnAdd" RunAt="server" />

serves the dual purpose of declaring a Button control and designating OnAdd as the handler for the Button control's Click events. That's why the code in OnAdd executed when you clicked the = button. Knowing this, it's a simple matter to consult the documentation for the list of events a control is capable of firing and connecting handlers to the events that interest you.

What happens under the hood to support the Web Forms event model is a little more complex. Look again at the HTML returned by Calc.aspx. Notice that it contains an HTML form and a submit button. Clicking the button posts the form back to the server using an HTTP POST. Recognizing that the POST command represents a postback that occurred because the user clicked the = button, ASP.NET notifies the Button object and the Button responds by firing a Click event on the server. ASP.NET subsequently calls OnAdd and then renders the page again into HTML. Because the Label control's Text property now has a non-null string assigned to it, this time the HTML output by the Label control includes a text string between the <span> and </span> tags.

Implementation Notes

Calc.aspx contains no code to prevent the numbers typed into the TextBox controls from disappearing following a postback. The <asp:TextBox> tags in Figure 5-6 lack Value attributes such as the ones in Figure 5-5's <input type= "text"> tags. Yet the inputs don't disappear when you click the = button. Why? Because TextBox controls automatically persist their contents across postbacks. Check the HTML returned to the browser following the postback and you'll find that <input type="text"> tags rendered by the TextBox controls have Value attributes that equal the text typed by the user.

Incidentally, to make Calc.aspx as simple as possible, I purposely omitted error checking code. To see what I mean, type something other than a simple integer value (say, "hello") into one of the text boxes and click the = button. The page you see is ASP.NET's way of responding to unhandled exceptions. To prevent this error, rewrite Calc.aspx's OnAdd method as follows:

void OnAdd (Object sender, EventArgs e){    try {        int a = Convert.ToInt32 (op1.Text);        int b = Convert.ToInt32 (op2.Text);        Sum.Text = (a + b).ToString ();    }    catch (FormatException) {        Sum.Text = "Error";    }}

This version of OnAdd catches the exception thrown when Convert.ToInt32 is unable to convert the input to an integer and responds by displaying the word "Error" to the right of the push button.


Editor's Note: This sample chapter continues in the article titled, Web Forms: The Web Forms Programming Model.

About the Author

Jeff Prosisemakes his living programming Microsoft .NET and teaching othershow to do the same. A former engineer who discovered after college that programming is immeasurably more fun than designing lifting fixtures and computing loads on mounting brackets, today Jeff travels the world for Wintellect, the company he co-founded in 2000, helping other companies get up to speed on Microsoft .NET. Programming Microsoft .NET is Jeff's ninth book.

Programming Microsoft .NET. Copyright 2002, Jeff Prosise. Reproduced by permission of Microsoft Press. All rights reserved.

# # #





Page 4 of 4



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel