Export (0) Print
Expand All
Expand Minimize

Introduction to ASP.NET and Web Forms

 

Paul D. Sheriff
PDSA, Inc.

November 2001

Summary: This article explains how Web Forms are fundamental to Microsoft ASP.NET, shows how to build a Web form, and discusses the controls essential for building a Web Form. (16 printed pages)

Objectives

  • Learn about Web Forms
  • Learn the Web controls that are built into Web Forms
  • Build a Web Form

Assumptions

The following should be true for you to get the most out of this document:

  • You are familiar with ASP development
  • You are familiar with HTTP and Internet development

Contents

Overview of ASP.NET and Web Forms
   The Purpose of Web Forms
   HTML Controls
   Web Form Controls
   Field Validator Controls
   Creating Custom Controls
   How Web Forms Work
   Global.asax
Create a Web Form
   Adding Code to the Button
Summary
   About the Author

Overview of ASP.NET and Web Forms

Microsoft® ASP.NET is the next generation technology for Web application development. It takes the best from Active Server Pages (ASP) as well as the rich services and features provided by the Common Language Runtime (CLR) and add many new features. The result is a robust, scalable, and fast Web development experience that will give you great flexibility with little coding.

Web Forms are the heart and soul of ASP.NET. Web Forms are the User Interface (UI) elements that give your Web applications their look and feel. Web Forms are similar to Windows Forms in that they provide properties, methods, and events for the controls that are placed onto them. However, these UI elements render themselves in the appropriate markup language required by the request, e.g. HTML. If you use Microsoft Visual Studio® .NET, you will also get the familiar drag-and-drop interface used to create your UI for your Web application.

Web Forms are made up of two components: the visual portion (the ASPX file), and the code behind the form, which resides in a separate class file.

Figure 1. Web Forms are a part of ASP.NET

The Purpose of Web Forms

Web Forms and ASP.NET were created to overcome some of the limitations of ASP. These new strengths include:

  • Separation of HTML interface from application logic
  • A rich set of server-side controls that can detect the browser and send out appropriate markup language such as HTML
  • Less code to write due to the data binding capabilities of the new server-side .NET controls
  • Event-based programming model that is familiar to Microsoft Visual Basic® programmers
  • Compiled code and support for multiple languages, as opposed to ASP which was interpreted as Microsoft Visual Basic Scripting (VBScript) or Microsoft Jscript®
  • Allows third parties to create controls that provide additional functionality

On the surface, Web Forms seem just like a workspace where you draw controls. In reality, they can do a whole lot more. But normally you will just place any of the various controls onto the Web Form to create your UI. The controls you use determine which properties, events, and methods you will get for each control. There are two types of controls that you can use to create your user interface: HTML controls and Web Form controls.

Let's look at the different types of controls that you can use in Web Forms and the ASP.NET Framework.

HTML Controls

HTML controls mimic the actual HTML elements that you would use if you were using Front Page or any other HTML editor to draw your UI. You can use standard HTML elements in Web Forms, too. For example, if you wanted to create a text box, you would write:

<input type="text" id=txtFirstName size=25>

If you are using Visual Studio .NET, you choose a TextField control from the HTML Toolbox tab and draw the control where you want it on the HTML page.

Any HTML element can be marked to also run as an HTML control when the Web Form is processed on the server by adding "runat=server" to the tag:

<input type="text" id=txtFirstName size=25 runat=server>

If you are using Visual Studio .NET, you can right-click the HTML element in Design View and select Run as Server Control from the context menu.

HTML controls allow you to handle server events associated with the tag (a button click, for example), and manipulate the HTML tag programmatically in the Web Form code. When the control is rendered to the browser, the tag is rendered just as it is saved in the Web Form, minus the "runat=server". This gives you precise control over the HTML that is sent to the browser.

Table 1. HTML controls available in ASP.NET

Control Description Web Form Code Example
Button A normal button that you can use to respond to Click events <input type=button runat=server>
Reset Button Resets all other HTML form elements on a form to a default value <input type=reset runat=server>
Submit Button Automatically POSTs the form data to the specified page listed in the Action= attribute in the FORM tag <input type=submit runat=server>
Text Field Gives the user an input area on an HTML form <input type=text runat=server>
Text Area Used for multi-line input on an HTML form <input type=textarea runat=server>
File Field Places a text field and a Browse button on a form and allows the user to select a file name from their local machine when the Browse button is clicked <input type=file runat=server>
Password Field An input area on an HTML form, although any characters typed into this field are displayed as asterisks <input type=password runat=server>
CheckBox Gives the user a check box that they can select or clear <input type=checkbox runat=server>
Radio Button Used two or more to a form, and allows the user to choose one of the controls <input type=radio runat=server>
Table Allows you to present information in a tabular format <table runat=server></table>
Image Displays an image on an HTML form <img src="FileName" runat=server>
ListBox Displays a list of items to the user. You can set the size from two or more to specify how many items you wish show. If there are more items than will fit within this limit, a scroll bar is automatically added to this control. <select size=2 runat=server ></select>
Dropdown Displays a list of items to the user, but only one item at a time will appear. The user can click a down arrow from the side of this control and a list of items will be displayed. <select><option></option></select>
Horizontal Rule Displays a horizontal line across the HTML page <hr>

All of these controls write standard HTML into the Web Form. You may optionally assign an ID attribute to each control, allowing you to write client-side JavaScript code for any of the events that are common for this particular type of control. Below is a partial list of some of the more common client-side events.

Table 2. Common client-side events

Control Description
OnBlur: Control loses focus
OnChange: Contents of the control are changed
OnClick: Control is clicked on
OnFocus: Control receives focus
OnMouseOver: Mouse moves over this control

Web Form Controls

Web Form controls are created and run on the Server just like the HTML controls. After performing whatever operation they are designed to do, they render the appropriate HTML and send that HTML into the output stream. For example, a DropDownList control will allow you to bind to a data source, yet the output that is rendered is standard <SELECT> and <OPTION> tags when sent to a browser. However, the same DropDownList control might render WML if the target is a portable phone. That is why these controls do not necessarily map to any one markup language, but have the flexibility to target the appropriate markup language.

All Web Form controls inherit from a common base class, namely the System.Web.UI.WebControls class. This base class implements a set of common properties that all of these controls will have. Some of these common properties are:

  • BackColor
  • Enabled
  • Font
  • ForeColor
  • Modifiers
  • TabIndex
  • Visible
  • Width

There are a few different categories of controls that are supplied by the Microsoft .NET Framework. Some controls have an almost one-to-one correspondence with their HTML counterparts. Some controls provide additional information when posted back to the server, and some controls allow you to display data in tabular or list-type format. Table 2 shows a list of Web Form server-side controls and the server-side events that you can respond to with each control.

Table 2. Server-side controls used in ASP.NET and Web Forms

Control Description Commonly Used Server-Side Events Web Form Code Example
Label Displays text on the HTML page None <asp:Label id=Label1 runat="server">Label</asp:Label>
TextBox Gives the user an input area on an HTML form TextChanged <asp:TextBox id=TextBox1 runat="server"></asp:TextBox>
Button A normal button control used to respond to click events on the server. You are allowed to pass additional information by setting the CommandName and CommandArguments properties. Click, Command <asp:Button id=Button1 runat="server" Text="Button"></asp:Button>
LinkButton Like a button in that it posts back to a server, but the button looks like a hyperlink Click, Command <asp:LinkButton id=LinkButton1 runat="server">LinkButton</asp:LinkButton>
ImageButton Can display a graphical image, and when clicked, posts back to the server command information such as the mouse coordinates within the image, when clicked Click <asp:ImageButton id=ImageButton1 runat="server"></asp:ImageButton>
Hyperlink A normal hyperlink control that responds to a click event None <asp:HyperLink id=HyperLink1 runat="server">HyperLink
</asp:HyperLink>
DropDownList A normal dropdown list control like the HTML control, but can be data bound to a data source SelectedIndexChanged <asp:DropDownList id=DropDownList1 runat="server"></asp:DropDownList>
ListBox A normal ListBox control like the HTML control, but can be data bound to a data source SelectedIndexChanged <asp:ListBox id=ListBox1 runat="server"></asp:ListBox>
DataGrid Like a <TABLE> on steroids. You bind a data source to this control and it displays all of the column information. You can also perform paging, sorting, and formatting very easily with this control. CancelCommand, EditCommand, DeleteCommand, ItemCommand, SelectedIndexChanged, PageIndexChanged, SortCommand, UpdateCommand, ItemCreated, ItemDataBound <asp:DataGrid id=DataGrid1 runat="server"></asp:DataGrid>
DataList Allows you to create a non-tabular type of format for data. You can bind the data to template items, which are like bits of HTML put together in a specific repeating format. CancelCommand, EditCommand, DeleteCommand, ItemCommand, SelectedIndexChanged, UpdateCommand, ItemCreated, ItemDataBound <asp:DataList id=DataList1 runat="server"></asp:DataList>
Repeater Allows you to create a non-tabular type of format for data. You can bind the data to template items, which are like bits of HTML put together in a specific repeating format. ItemCommand, ItemCreated, ItemDataBound <asp:Repeater id=Repeater1 runat="server"></asp:Repeater>
CheckBox Very similar to the normal HTML control that displays a check box for the user to check or uncheck CheckChanged <asp:CheckBox id=CheckBox1 runat="server"></asp:CheckBox>
CheckBoxList Displays a group of check boxes that all work together SelectedIndexChanged <asp:CheckBoxList id=CheckBoxList1 runat="server"></asp:CheckBoxList>
RadioButton Very similar to the normal HTML control that displays a button for the user to check or uncheck CheckChanged <asp:RadioButton id=RadioButton1 runat="server"></asp:RadioButton>
RadioButtonList Displays a group of radio button controls that all work together SelectedIndexChanged <asp:RadioButtonList id=RadioButtonList1 runat="server"></asp:RadioButtonList>
Image Very similar to the normal HTML control that displays an image within the page None <asp:Image id=Image1 runat="server"></asp:Image>
Panel Used to group other controls None <asp:Panel id=Panel1 runat="server">Panel</asp:Panel>
PlaceHolder Acts as a location where you can dynamically add other server-side controls at run time None <asp:PlaceHolder id="PlaceHolder1" runat="server"></asp:PlaceHolder>
Calendar Creates an HTML version of a calendar. You can set the default date, move forward and backward through the calendar, etc. SelectionChanged, VisibleMonthChanged, DayRender <asp:Calendar id=Calendar1 runat="server"></asp:Calendar>
AdRotator Allows you to specify a list of ads to display. Each time the user re-displays the page, the display rotates through the series of ads. AdCreated <asp:AdRotator id=AdRotator1 runat="server"></asp:AdRotator>
Table Very similar to the normal HTML control None <asp:Table id=Table1 runat="server"></asp:Table>
XML Used to display XML documents within the HTML, It can also be used to perform an XSLT transform prior to displaying the XML. None <asp:Xml id="Xml1" runat="server"></asp:Xml>
Literal Like a label in that it displays a literal, but allows you to create new literals at runtime and place them into this control None <asp:Literal id="Literal1" runat="server"></asp:Literal>

All of these controls change their output based on the type of browser detected for the user. If the user's browser is IE, a richer look and feel can be generated using some DHTML extensions. If a down-level browser is detected (something other than IE), normal HTML 3.2 standard is sent back to the user's browser.

Field Validator Controls

Another type of Web Form control validates data on the client browser, before the user submits the data to the back-end server. If the user fills in some data into a group of controls on an HTML page, you normally have to send all the data back to the server so it can be validated by either your ASP or ASP.NET code. Instead of having to do this round trip just to check to see if a value has been filled in, you can use one of the Field Validator controls to perform this client check. Each of these controls writes client-side JavaScript code into the HTML page so the values can be checked without the round-trip. The JavaScript works on all browsers.

Table 3. Field Validator controls

Control Description HTML or JavaScript Code Example
RequiredFieldValidator Allows you to check a control on the form to see if it is filled in with anything. If it isn't, the ErrorMessage that you set will be displayed in this control. <asp:RequiredFieldValidator
id=RequiredFieldValidator1
runat="server"
ErrorMessage=
"RequiredFieldValidator">
</asp:RequiredFieldValidator>
CompareValidator Allows you to check the contents of one control against the contents of another control on the form to see if they match. If they don't, the ErrorMessage that you set will be displayed into this control. <asp:CompareValidator
id=CompareValidator1
runat="server"
ErrorMessage=
"CompareValidator">
</asp:CompareValidato>
RangeValidator Allows you to check to see whether the value you entered in a control is within a specified range. If it isn't, the ErrorMessage that you set will be displayed into this control. <asp:RangeValidator
id=RangeValidator1
runat="server"
ErrorMessage=
"RangeValidator">
</asp:RangeValidator>
RegularExpressionValidator Allows you to check to see if a control's contents match the input mask (regular expression) you defined. If it doesn't, the ErrorMessage that you set will be displayed into this control. <asp:RegularExpressionValidator
id=RegularExpressionValidator1
runat="server" ErrorMessage=
"RegularExpressionValidator">
</asp:RegularExpressionValidator>
CustomValidator Allows you to specify either a server-side or client-side script function to validate the contents of a particular control. You must return a True or False value from these functions. If a True value is returned, processing continues; if a False value is returned, the ErrorMessage specified for this control is displayed. <asp:CustomValidator
id=CustomValidator1
runat="server"
ErrorMessage=
"CustomValidator">
</asp:CustomValidator>

These Field Validator controls are wonderful tools for allowing you to check the user's input without a round trip back to the server.

Creating Custom Controls

In addition to the built-in controls in the .NET Framework, you can also build your own custom controls. For example, you may wish to create a menu system where each menu item is built from a database.

How Web Forms Work

Just like in Windows Forms, there are events that fire in a certain order when a Web Form initializes and loads. There are also events that fire in response to user interaction in the browser with the rendered page. When you think about how a standard ASP or HTML is created and sent to a browser, you assume that everything is processed in a very linear, top-down fashion. However, for a Web Form, nothing could be further from the truth.

Like a Windows Form, a Web Form, goes through the standard Load, Draw (Render), and Unload types of events. Throughout this process, different procedures within the class module are called. When a page is requested from a client browser, a DLL that encapsulates both the tags in the ASPX page, as well as the page code, is loaded, then processed.

First, the Init event sets the page to its initial state as described by the tags in the ASPX file. If the page is posting back to itself, Init also restores any page state that may have been stored in "viewstate". If you wish, your code can also handle the Page_Init() event to further customize the initial state of the page.

Next, the Load event fires. The Load event is where you can check to see if this is the first time this page has been loaded, or whether this is a post back from the user hitting a button or other control on that page. You might perform some initialization only on the first page load, for example bind data into the controls.

Next, and only if the page is posted back, control events are fired. First, all of the "change" events are fired. These events are batched up in the browser, and execute only when the page is sent back to the server. Examples include changing the text in a text box, or the selection of a list.

Next, and only if the page is posted back, the control event that caused the page to post back is fired. Examples of postback events include button click, or "autopostback" change events like a check box CheckedChanged event.

Next, the page is rendered to the browser. Some state information ("viewstate") is included in a hidden field in the page so when the page is called again through a post back, ASP.NET can restore the page to its previous state.

There is a final page event your code can handle before the page is disposed: Page_Unload(). Since the page is already rendered, this event is typically used to perform cleanup and logging tasks only. Finally, the class that represents the running page is disposed, and the page is unloaded from server memory.

If you change the ASPX page or its code, the dynamically generated DLL that represents the page will be regenerated the next time the page is requested. This DLL is stored to disk each time it is generated.

Global.asax

The Global.asax file is similar to the Global.asa file in ASP, albeit that there are many more events available in ASP.NET. Also, Global.asax is compiled instead of interpreted as it is in ASP. You still have event procedures that fire within the Global.asax file when certain events happen on your Web site. In the following list, you will find the event procedures that are available to you within the Global.asax file.

Table 4. Event procedures available within Global.asax

Event Procedure Description
Application_Start Fires when the first user hits your Web site
Application_End Fires when the last user in the site's session times out
Application_Error Fires when an unhandled error occurs in the application
Session_Start Fires when any new user hits your Web site
Session_End Fires when a user's session times out or ends
Application_AcquireRequestState Fires when ASP.NET acquires the current state (for example, session state) associated with the current request
Application_AuthenticateRequest Fires when a security module establishes the identity of the user
Application_AuthorizeRequest Fires when a security module verifies user authorization
Application_BeginRequest Fires when ASP.NET starts to process the request, before other per-request events
Application_Disposed Fires when ASP.NET completes the chain of execution when responding to a request
Application_EndRequest Fires as the last event during the processing of the request, after other pre-request events
Application_PostRequestHandlerExecute Fires right after the ASP.NET handler (page, XML Web service) finishes execution
Application_PreRequestHandlerExecute Fires just before ASP.NET begins executing a handler such as a page or XML Web service
Application_PreSendRequestContent Fires just before ASP.NET sends content to the client
Application_PreSendRequestHeaders Fires just before ASP.NET sends HTTP headers to the client
Application_ReleaseRequestState Fires after ASP.NET finishes executing all request handlers. This event causes state modules to save the current state data
Application_ResolveRequestCache Fires after ASP.NET completes an authorization event to let the caching modules serve requests from the cache, bypassing execution of the handler (the page or Web service, for example).
Application_UpdateRequestCache Fires after ASP.NET finishes executing a handler in order to let caching modules store responses that will be used to serve subsequent requests from the cache

Create a Web Form

Let's create a Web Form that allows a user to input their first and last names. After entering the data into these two text fields on the Web page, the user clicks a login button and the user's Last name, First name appear in a label below the login button.

Figure 2 shows the sample login Web Form that you will use.

Figure 2: Sample showing how to enter data and display it back into a label control

To build a Login form

  1. Open Visual Studio and, on the Start page, click Create New Project.
  2. Highlight Visual Basic Projects from the treeview on the left.
  3. In the Templates window, click Web Application.
  4. For the Name of this project, type WebForms101.
  5. Choose the location of the machine where you wish to create this Web site.
  6. Click OK to begin the process of creating the new Web Application project.
  7. You should now have a Web Form named WebForm1.aspx in your Visual Studio project. Rename this form to Login.aspx.
  8. Open the Toolbox and create the form in Figure 3 by adding the appropriate controls and setting the properties of those controls as outlined in Table 5.

    Table 5. Controls used to build the Login form

    Control Type Property Value
    Label Name Label1
      Text First Name
    TextBox Name txtFirst
      Text  
    Label Name Label2
      Text Last Name
    TextBox Name txtLast
      Text  
    Button Name btnSubmit
      Text Login
    Label Name lblName
      BorderStyle Insert
      Text  

Try It Out

At this point, you can run this application and see this Web Form appear in your browser. Although this page does not have any functionality yet, this exercise is a good test to make sure everything is running up to this point.

  1. Press F5 to run this sample application.
  2. If you receive an error message informing you that you need a start page, right-click the Login.aspx page and click Set as Start Page from the context menu.

You should now see the Web Form displayed in your browser, and you can enter data into the two text fields. If you click the Login button, nothing will happen because you have not told it to do anything yet. You will next learn how to make this Login button do something.

Adding Code to the Button

Let's add some code to the button so that it posts the data you entered in the text boxes, and fills in the appropriate data in the label below the button control.

  1. End the program by closing down the browser.
  2. While looking at the Login page in design mode, double-click the Login button control. You will now see a code window appear with the event procedure btnSubmit. Right-click by your cursor.
  3. Fill in the Click event procedure so it looks like the following code.
    Public Sub btnSubmit_Click(ByVal sender As Object, _
     ByVal e As System.EventArgs) Handles btnSubmit.Click
        lblName.Text = txtLast.Text & ", " & txtFirst.Text
    End Sub
    

What you have just done is retrieved the text property from both the txtLast and txtFirst text boxes and placed the data into the label control below the Login button. This should look very familiar, if you have ever programmed in Visual Basic. In fact, the whole point of .NET is that all of the coding, whether for Windows applications or Web applications, should look the same.

Summary

Using HTML pages, ASPX (Web Form) pages, HTML controls, and Web Form controls, you now have a fantastic RAD environment for creating very robust, scalable, and flexible Web applications in ASP.NET. You should find that the move to ASP.NET is easier than moving from Visual Basic 6.0 to ASP development as you now have the same development environment and the same programming model.

About the Author

Paul D. Sheriff is the owner of PDSA, Inc., a custom software development and consulting company in Southern California. Paul is the MSDN Regional Director for Southern California, is the author of a book on Visual Basic 6 called Paul Sheriff Teaches Visual Basic, and has produced over 70 videos on Visual Basic, SQL Server, .NET and Web Development for Keystone Learning Systems. Paul has co-authored a book entitled ASP.NET Jumpstart. Visit the PDSA, Inc. Web site (www.pdsa.com) for more information.

About Informant Communications Group

Informant Communications Group, Inc. (www.informant.com) is a diversified media company focused on the information technology sector. Specializing in software development publications, conferences, catalog publishing and Web sites, ICG was founded in 1990. With offices in the United States and the United Kingdom, ICG has served as a respected media and marketing content integrator, satisfying the burgeoning appetite of IT professionals for quality technical information.

Copyright © 2001 Informant Communications Group and Microsoft Corporation

Technical Editing: PDSA, Inc.

Show:
© 2014 Microsoft