Completing a Web Form in ASP.NET

Before you can build your first ASP.NET application, there are certain skills you need to master. This article, the third of three parts, rounds out what you need to know to build a web form. It is excerpted from the book Murach's ASP.NET 2.0 Web Programming with VB2005, written by Doug Lowe (Murach, 2006; ISBN: 1890774324).

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 29
June 15, 2006
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

How to add validation controls to a form

A validation control is a type of ASP.NET control that’s used to validate input data. The topics that follow introduce you to the validation controls and show you how to use two of the commonly used controls. Then, in chapter 7, you can learn all the skills that you need to master the use of these controls.

An introduction to the validation controls

Figure 2-12 shows the Validation group in the Toolbox. It offers five controls that can be called validators. These are the controls that you use to check that the user has entered valid data. You can use the last control in this group, the validation summary control, to display all the errors that have been detected by the validators on the form.

The easiest way to add a validation control to a web form is to drag it from the Toolbox. In this example, four validators have been added to the form: two required field validators and two range validators. In this case, the controls have been added below the table so ASP.NET will use flow layout to position the controls. However, these controls could have been added to a third column of the table. Although these controls aren’t displayed when the form is displayed, the messages in their ErrorMessage properties are displayed if errors are detected.

In this case, the first required field validator checks to make sure that a value has been added to the text box for the interest rate, and the first range validator checks to make sure that this value ranges from 1 to 20. Similarly, the second required field validator checks to make sure that a value has been entered in the text box for years, and the second range validator checks to make sure that this value ranges from 1 to 45.

Validation tests are typically done on the client before the page is posted to the server. That way, a round trip to the server isn’t required to display error messages if any invalid data is detected.

In most cases, client-side validation is done when the focus leaves an input control that has validators associated with it. That can happen when the user presses the Tab key to move to the next control or clicks another control to move the focus to that control. Validation is also done when the user clicks on a button that has its CausesValidation property set to True.

To perform client-side validation, a browser must support Dynamic HTML, or DHTML. Because most browsers in use today support DHTML, validation can usually be done on the client. However, validation is always done on the server too when a page is submitted. ASP.NET does this validation after it initializes the page.

When ASP.NET performs the validation tests on the server, it sets the IsValid property of each validator to indicate if the test was successful. In addition, after all the validators are tested, it sets the IsValid property of the page to indicate if all the input data is valid. You can test this property in the event handler for the event that causes the page to be posted to the server. You’ll see how this works when you review the code-behind file for this form. 

The validation controls on the Future Value form


Figure 2-12.  An introduction to the validation controls

Description

  1. You can use validation controls to test user input and produce error messages. The validation is performed when the focus leaves the control that’s being validated and also when the user clicks on a button control whose CausesValidation property is set to True.
  2. Each validation control is associated with a specific server control, but you can associate one or more validation controls with a single server control.
  3. The validation controls work by running client-side script. Then, if the validation fails, the page isn’t posted back to the server. However, the validation is also performed on the server in case the client doesn’t support scripts.
  4. If the client doesn’t support scripts, you can test whether validation has been successful on the server by testing whether the IsValid property of the page is True.

How to use the required field validator

To use the required field validator, you set the properties shown in the table at the top of figure 2-13. These are the properties that are used by all the validators.

To start, you associate the validation control with a specific input control on the form through its ControlToValidate property. Then, when the focus leaves the input control or the user clicks on a button whose CausesValidation property is set to True, the validator checks whether a value has been entered into the input control. If not, the message in the ErrorMessage property is displayed.

When an error occurs, the Display property of the validation control determines how the message in the ErrorMessage property is displayed. When you use flow layout, Dynamic usually works the best for this property. If you use a validation summary control as explained in chapter 7, though, you can change this property to None.

If you look at the aspx code in this figure, you can see how the properties are set for the two required field validators that are shown in the previous figure. The first one validates the text box named txtInterestRate. The second one validates the text box named txtYears. This aspx code will be added after the end tag for the table in the code in figure 2-11.

How to use the range validator

The range validator lets you set the valid range for an input value. To use this control, you set the properties in the first table in figure 2-13, plus the properties in the second table. In particular, you set the minimum and maximum values for an input value.

For this control to work correctly, you must set the Type property to the type of data you’re testing for. Because the interest rate entry can have decimal positions, for example, the Type property for the first range validator is set to Double. In contrast, because the year entry should be a whole number, the Type property for the second range validator is set to Integer. You can see how all of the properties for the two range validators are set by reviewing the aspx code.

Common validation control properties

Property

Description

ControlToValidate

The ID of the control to be validated.

Display

Determines how an error message is displayed. Specify Static to allocate space for the message in the page layout, Dynamic to have the space allocated when an error occurs, or None to display the errors in a validation summary control.

ErrorMessage

The message that’s displayed in the validation control when the validation fails.

Additional properties of a range validator

Property

Description

Maximum

The maximum value that the control can contain.

Minimum

The minimum value that the control can contain.

Type

The data type to use for range checking (String, Integer, Double, Date, or Currency).

The aspx code for the validation controlson the Future Value form

  <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"  
      ControlToValidate= "txtInterestRate" Display="Dynamic"
      ErrorMessage="Interest rate is required.">

  </asp:RequiredFieldValidator>

  <asp:RangeValidator ID="RangeValidator1" runat="server" 
      ControlToValidate= "txtInterestRate" Display="Dynamic"
      ErrorMessage="Interest rate must range from 1 to 20."
      MaximumValue="20" MinimumValue="1" Type="Double">

  </asp:RangeValidator><br />

  <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
      ControlToValidate="txtYears" Display="Dynamic"
      ErrorMessage="Number of years is required.">

  </asp:RequiredFieldValidator>

  <asp:RangeValidator ID="RangeValidator2" runat="server"
      ControlToValidate="txtYears" Display="Dynamic"
      ErrorMessage="Years must range from 1 to 45."
      MaximumValue="45" MinimumValue="1" Type="Integer">
  </asp:RangeValidator>

Figure 2-13. How to use the required field and range validators

Description

  1. The required field validator is typically used with text box controls, but can also be used with list controls.
  2. The range validator tests whether a user entry falls within a valid range.
  3. If the user doesn’t enter a value into the input control that a range validator is associated with, the range validation test passes. Because of that, you should also provide a required field validator if a value is required.

How to add code to a form

To add the functionality required by a web form, you add Visual Basic code to its code-behind file. This code responds to the events that the user initiates on the form. This code also responds to events that occur as a form is processed.

How to use the Code Editor

To create and edit Visual Basic code, you use the Code Editor shown in figure 2-14. The easiest way to display the Code Editor window is to double-click the form or a control in the Web Forms Designer window. That displays the code-behind file for the form.

If you double-click the form in Design view, Sub and End Sub statements for the Load event of the page are generated. If you double-click a control, Sub and End Sub statements for the default event of the control are generated. If you double-click on a button control, for example, an event procedure (or event handler) for the Click event of that control is created. Then, you can enter the code for that procedure between the generated Sub and End Sub statements.

To create procedures for other events, you can use the drop-down lists at the top of the Code Editor window. The list at the left side of the window includes all of the available objects. When you select one of these objects, the list at the right side of the window lists all the events for that object. When you select an event, Visual Studio generates Sub and End Sub statements for the event handler.

You can also code general procedures by entering code directly into the Code Editor window. To create a Sub procedure, for example, you enter a Sub statement. And to create a Function procedure, or just function, you enter a Function statement. When you press the Enter key after entering one of these statements, the End Sub or End Function statement is generated for you. Then, you can enter the code required to implement the procedure between these statements, and you can call the procedure from another procedure.

As you work with the Code Editor, you’ll notice that it provides some powerful features that can help you code more quickly and accurately. One of the most useful of these features is the Auto List Members feature provided by IntelliSense. This feature displays a list of members that are available for an object when you type the object name and a period. Then, you can highlight the member you want by clicking on it, typing the first few letters of its name, or using the arrow keys to scroll through the list. In this figure, you can see the members that are listed for a drop-down list after the first character of the member name is entered. When you press the Tab key, the member you select is inserted into your code.

You can also use the Text Editor toolbar to work with code in the Code Editor. You can use it to perform functions such as commenting or uncommenting several lines of code at once, increasing or decreasing the indentation of several lines of code, and working with bookmarks. If you experiment with this toolbar, you should quickly see how it works.

A project with the Code Editor window displayed


Figure 2-14.  How to use the Code Editor

Three ways to open or switch to a file in the Code Editor window

  • Select a web form in the Solution Explorer and click the View Code button at the top of the Solution Explorer. Double-click on a Visual Basic file (.aspx.vb or .vb) in the Solution Explorer. Or, click on a tab at the top of the Web Forms Designer (if the file is already open).

Four ways to start an event procedure

  1. Double-click on a blank portion of a web form to start an event procedure for the Load event of the page.
  2. Double-click on a control in the Web Forms Designer to start an event procedure for the default event of that control.
  3. Select a control in the Web Forms Designer, click the Events button in the Properties window (the button with the lightening bolt), and double-click the event you want to create an event procedure for.
  4. Select a control from the drop-down list at the top left of the Code Editor window, and select an event from the drop-down list at the top right. To create an event procedure for a page event, select (Page Events) from the first drop-down list.

Description

  1. The Code Editor includes powerful text editing features such as automatic indentation, syntax checking, and statement completion (as shown above).
  2. To enter a Sub procedure or function, you type the procedure or function from scratch, but Visual Studio will insert the End Sub or End Function statement.

How to use page and control events

The first table in figure 2-15 presents some of the common events for working with web pages. The Init and Load events of a page occur whenever a page is requested from the server. The Init event occurs first, and it’s used by ASP.NET to restore the view state of the page and its controls. Because of that, you don’t usually create an event handler for this event. Instead, you add any initialization code to the event handler for the Load event. You’ll see how this works in the next figure.

In contrast, the PreRender event is raised after all the control events for the page have been processed. It’s the last event to occur before a page is rendered to HTML. In later chapters, you’ll see a couple of cases in which this event is useful.

The second table in this figure lists some of the common events for web server controls. When the user clicks a button, for example, the Click event of that control is raised. Then, the page is posted back to the server, the event handlers for the Init and Load events of the page are executed, if present, followed by the event handler for the Click event of the control that was clicked.

The TextChanged event occurs when the user changes the value in a text box. In most cases, you won’t code an event handler for the TextChanged event. However, you might code an event handler for the CheckedChanged event that occurs when the user clicks a radio button or checks a check box. You might also code an event handler for the SelectedIndexChanged event that occurs when the user selects an item from a drop-down list.

If you want the event handler for one of these events to be executed immediately when the event occurs, you can set the AutoPostBack property of the control to True. Then, the event handler will be executed after the Load and Init event handlers for the page. Note that if you don’t set the AutoPostBack property to True, the event is still raised, but the event handler isn’t executed until another user action causes the page to be posted to the server. Then, the event handlers for the Load and Init events of the page are executed, followed by the event handlers for the control events in the order they were raised.

In this figure, you can see the event handler for the Click event of the Clear button on the Future Value form. Note that the name for this event handler is btnClear_Click, which is the ID of the button followed by the name of the event. Remember, though, that the Handles clause actually determines what event or events the procedure responds to. In this procedure, the value in the drop-down list is reset to 50, and the text boxes and label are reset to empty strings.

Incidentally, using the Handles clause is the default method for wiring events to their event handlers. However, you can also wire an event to an event handler by naming the event handler on the event attribute of a control. Although you’ll learn how this works in chapter 6, there’s usually no reason to change from using the Handles clause.

Common ASP.NET page events

Event

Procedure name

Occurs when…

Init

Page_Init

A page is requested from the server. This event is raised before the view state of the page controls has been restored.

Load

Page_Load

A page is requested from the server, after all controls have been initialized and view state has been restored. This is the event you typically use to perform initialization operations such as retrieving data and initializing form controls.

PreRender

Page_PreRender

All the control events for the page have been processed but before the HTML that will be sent back to the browser is generated.

Common ASP.NET control events

Event

Occurs when…

Click

The user clicks a button, link button, or image button control.

TextChanged

The user changes the value in a text box.

CheckedChanged

The user selects a radio button in a group of radio buttons or selects or unselects a check box.

SelectedIndexChanged

The user selects an item from a list box, a drop-down list, a check box list, or a radio button list.

Code for the Click event of the btnClear button

  Protected Sub btnClear_Click(ByVal sender As Object, _
         
ByVal e As System.EventArgs) Handles btnClear.Click
     ddlMonthlyInvestment.Text = 50
     txtInterestRate.Text = ""
     txtYears.Text = ""
     lblFutureValue.Text = ""
 
End Sub

Figure 2-15. How to use page and control events

Description

  1. All of the events associated with an ASP.NET web page and its server controls are executed on the server. Because of that, the page must be posted back to the server to process any event for which you’ve coded an event handler.
  2. When a page is posted back to the server, the Init and Load events are always raised so any event handlers for those events are run first. Next, the event handlers for any control events that were raised are executed in the ordered they were raised. When these event handlers finish, the PreRender event is raised and any event handler for that event is run.

All of the events associated with an ASP.NET web page and its server controls are executed on the server. Because of that, the page must be posted back to the server to process any event for which you’ve coded an event handler.

The Visual Basic code for the Future Value form

Figure 2-16 presents the complete Visual Basic code for the code-behind file of the Future Value form. It consists of three event handlers that handle the Load event for the page and the Click events of the Calculate and Clear buttons. This code also includes a function procedure named FutureValue that is called by the event handler for the Click event of the Calculate button.

In this code, I’ve highlighted the two page properties that are commonly tested in the code for web forms. The first one is the IsPostBack property that’s used in the Page_Load procedure. If it is True, it means that the page is being posted back from the user. If it is False, it means that the page is being requested by the user for the first time.

As a result, the statements within the If statement in the Page_Load procedure are only executed if the page is being requested for the first time. In that case, the values 50 through 500 are added to the drop-down list. For all subsequent requests by that user, the IsPostBack property will be True so the values aren’t added to the drop-down list.

The other page property that’s commonly tested is the IsValid property. It’s useful when the user’s browser doesn’t support the script for the validation controls. In that case, the application has to rely on the validation that’s always done on the server. Then, if IsValid is True, it means that all of the input data is valid. But if IsValid is False, it means that one or more controls contain invalid input data so the processing shouldn’t be done.

In the btnCalculate_Click procedure, you can see how the IsValid test is used. If it isn’t True, the processing isn’t done. But otherwise, this procedure gets the years and interest rate values from the text boxes and converts them to monthly units. Then, it uses the SelectedValue property of the drop-down list to get the value of the selected item, which represents the investment amount. Last, it calls the FutureValue function to calculate the future value, uses the FormatCurrency method to format the future value, and puts the formatted value in the label of the form. When this procedure ends, the web form is sent back to the user’s browser.

With the exception of the IsPostBack and IsValid properties, this is all standard Visual Basic code so you shouldn’t have any trouble following it. But if you do, you can quickly upgrade your Visual Basic skills by getting our latest Visual Basic book.

The Visual Basic code for the Future Value form

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, _
             ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim iIndex As Integer
            For iIndex = 50 To 500 Step 50
                ddlMonthlyInvestment. Items.Add(iIndex)
            Next iIndex
        End If
    End Sub
   
Protected Sub btnCalculate_Click(ByVal sender As Object, _
           
ByVal e As System.EventArgs) Handles btnCalculate.Click
        Dim iMonths As Integer
        Dim dInterestRate, dMonthlyInvestment As Decimal
        Dim dFutureValue As Decimal
        If IsValid Then
           
iMonths = txtYears.Text * 12
            dInterestRate = txtInterestRate.Text / 12 / 100 
            dMonthlyInvestment = ddlMonthlyInvestment.SelectedValue
            dFutureValue = FutureValue(iMonths, dInterestRate, dMonthlyInvestment)
            lblFutureValue.Text = FormatCurrency(dFutureValue)
       
End If
    End Sub
   
Private Function FutureValue(ByVal Months As Integer, _
            ByVal InterestRate As Decimal, _
            ByVal MonthlyInvestment As Decimal) As Decimal
       
Dim iIndex As Integer
        Dim dFutureValue As Decimal
        For iIndex = 1 To Months
            dFutureValue = (dFutureValue + MonthlyInvestment) _
                        
* (1 + InterestRate)
        Next iIndex
        Return dFutureValue
   
End Function
   
Protected Sub btnClear_Click(ByVal sender As Object, _
            ByVal e As System.EventArgs) Handles btnClear.Click
        ddlMonthlyInvestment.Text = 50
        txtInterestRate.Text = "" 
        txtYears.Text = "" 
        lblFutureValue.Text = ""
    End Sub
End Class

Figure 2-16. The Visual Basic code for the Future Value form

How to test a web application

After you design the forms and develop the code for a web application, you need to test it to be sure it works properly. Then, if you discover any errors in the application, you can debug it, correct the errors, and test it again.

In chapter 4, you’ll learn all the skills you need to test and debug a web application. For now, I just want to show you how to run a web site with the built-in development server so you can test any applications that you develop for this chapter. Then, I’ll show you the HTML code that’s sent to the browser so you can see how that works.

How to run a web site with the built-in development server

When you run a file-system web site by using one of the techniques in figure 2-17, Visual Studio 2005 compiles the application. If the application compiles without errors, Visual Studio automatically launches the built-in ASP.NET 2.0 Development Server and displays the starting page of the web site in your default browser. Then, you can test the application to make sure that it works the way you want it to.

However, if any errors are detected as part of the compilation, Visual Studio opens the Error List window and displays the errors. These can consist of errors that have to be corrected as well as warning messages. In this figure, all of the errors have been corrected, but 7 warning messages are displayed in the Error List window.

To fix an error, you can double-click on it in the Error List window. This moves the cursor to the line of code that caused the error in the Code Editor. By moving from the Error List window to the Code Editor for all of the messages, you should be able to find the coding problems and fix them.

As you’re testing an application with the development server, exceptions may occur. If an exception isn’t handled by the application, ASP.NET switches to the Code Editor window and highlights the statement that caused the exception. In this case, you can end the application by clicking on the Stop Debugging button in the Debug toolbar or using the Debug->Stop Debugging command. Then, you can fix the problem and test again.

In chapter 4, you’ll learn all of the debugging skills that you’ll need for more complex applications. For simple applications, though, you should be able to get by with just the skills you have right now.

An ASP.NET project with the shortcut menu for a web form displayed


Figure 2-17.  How to run a web site with the built-in development server

How to run an application

  • Click on the Start button in the Standard toolbar or press F5. Then, the project is compiled and the starting page is displayed in your default browser.
  • The first time you run an ASP.NET application, a dialog box will appear asking whether you want to modify the web.config file to enable debugging. Click the OK button to proceed.

    How to stop an application
  • Click the Close button in the upper right corner of the browser. Or, if an exception occurs, click the Stop Debugging button in the Debug toolbar or press Shift+F5. 

    How to fix build errors
     
  • If any errors are detected when the project is compiled, an Error List window is opened and a list of errors is displayed along with information about each error. To display the source code that caused an error, double-click on the error in the Error List window.
  • After you’ve fixed all of the errors, run the application again, and repeat this process if necessary. Note, however, that you don’t have to fix the warnings.

How to review the HTML that’s sent to the browser

To view the HTML for a page that’s displayed in a browser, you can use the Source command in your browser’s View menu. To illustrate, figure 2-18 presents the HTML that’s sent back to the browser after I selected a new value from the drop-down list, entered new values into the text boxes, and clicked the Calculate button. Although you’ll rarely need to view this code, it does give you a better idea of what’s going on behind the scenes.

First, you’ll see that this code doesn’t include any asp tags. That’s because these tags are rendered to standard HTML so the controls they represent can be displayed in the browser. For instance, the asp tag for the drop-down list in the first row of the table has been converted to an HTML select tag.

Second, you can see that the view state data is stored in a hidden input field named _ViewState. Here, the value of this field is encrypted so you can’t read it. Because the data in view state is passed to and from the browser automatically, you don’t have to handle the passing of this data in your code.

Third, you can see that the data that I selected from the drop-down list is included in the HTML. Although you can’t see it, the data that was entered into the text boxes is included as well. This illustrates that you don’t need view state to save the information that’s entered by the user. Instead, view state is used to maintain the state of properties that have been set by code. For example, it’s used to maintain the values that are loaded into the drop-down list the first time the user requests the form.

Keep in mind that this HTML is generated automatically by ASP.NET, so you don’t have to worry about it. You just develop the application by using Visual Studio in the way I’ve just described, and the rest of the work is done for you.

The HTML for the Future Value form after a post back


Figure 2-18.  How to review the HTML that's sent to the browser 

Description

  • To view the HTML for a page, use the View->Source command in the browser’s menu.
  • The HTML that the browser receives consists entirely of standard HTML tags because all of the ASP.NET tags are converted to standard HTML when the page is rendered.
  • View state data is stored in a hidden input field within the HTML. This data is encrypted so you can’t read it.
  • If the page contains validation controls and client scripting is enabled for those controls, the HTML for the page contains script to perform the validation on the client if the client supports DHTML.
  • Values that the user enters into a page are returned to the browser as part of the HTML for the page.
blog comments powered by Disqus
ASP.NET ARTICLES

- Implementing ASP.NET 4.0 Page.MetaDescriptio...
- ASP.Net Development Tips
- Intro to Sessions in ASP.Net
- Google Maps API Introduction in ASP.NET usin...
- Creating an ASP.NET 3.5 Gridview Image Galle...
- Encrypt QueryString in ASP.NET 3.5 using VB....
- ASP.NET 3.5 Drop Down List Controls
- Connect to Access Database with ASP.Net
- Secure Audio Streaming with ASP.Net and Flash
- Dynamic Sitemap and Navigation in ASP.Net
- Implement Gzip and Deflate Compression in AS...
- Run ASP.Net in Ubuntu with Apache
- ASP.Net Mono Website Contact Forms
- ASP.Net URL Rewriting Methods
- Murach`s ASP.NET 4 Web Programming with C# 2...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 7 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials