Working with Forms

By Microsoft ASP.NET Team|June 22, 2010

A form is a section of an HTML document where you put user-input controls, like text boxes, check boxes, radio buttons, and pull-down lists. You use forms when you want to collect and process user input.

What you'll learn:

  • How to create an HTML form.
  • How to read user input from the form.
  • How to validate user input.
  • How to restore form values after the page is submitted.

These are the ASP.NET programming concepts introduced in the chapter:

  • The Request object.
  • Input validation.
  • HTML encoding.

Creating a Simple HTML Form

  1. Create a new website.

  2. In the root folder, create a web page named Form.cshtml and enter the following markup:

    <!DOCTYPE html>
    <html>
        <head>
            <title>Customer Form</title>
        </head>
        <body>
          <form method="post" action="">
            <fieldset>
              <legend>Add Customer</legend>
              <div>
                <label for="CompanyName">Company Name:</label>
                <input type="text" name="CompanyName" value="" />
              </div>
              <div>
                <label for="ContactName">Contact Name:</label>
                <input type="text" name="ContactName" value="" />
              </div>
              <div>
                <label for="Employees">Employee Count:</label>
                <input type="text" name="Employees" value="" />
              </div>
              <div>
                <label> </label>
                <input type="submit" value="Submit" class="submit" />
              </div>
            </fieldset>
          </form>
        </body>
    </html>
  3. Launch the page in your browser. (Make sure the page is selected in the Files workspace before you run it.) A simple form with three input fields and a Submit button is displayed.

    ch04_forms-1

    At this point, if you click the Submit button, nothing happens. To make the form useful, you have to add some code that will run on the server.

Reading User Input From the Form

To process the form, you add code that reads the submitted field values and does something with them. This procedure shows you how to read the fields and display the user input on the page. (In a production application, you generally do more interesting things with user input. You'll do that in the chapter about working with databases.)

  1. At the top of the Form.cshtml file, enter the following code:

    @{
        if (IsPost) {
            string companyname = Request["companyname"];
            string contactname = Request["contactname"];
            int employeecount = Request["employees"].AsInt();
    
            <text>
              You entered: <br />
              Company Name: @companyname <br />
              Contact Name: @contactname <br />
              Employee Count: @employeecount <br />
            </text>
        }
    }

    The way this page works, when the user first requests the page, only the empty form is displayed. The user (which will be you) fills in the form and then clicks Submit. This submits (posts) the user input to the server. The request goes to the same page (namely, Form.cshtml) because when you created the form in the previous procedure, you left the action attribute of the form element blank:

    <form method="post" action="">

    When you submit the page this time, the values you entered are displayed just above the form:

    ch04_forms-2

    Look at the code for the page. You first use the IsPost method to determine whether the page is being posted — that is, whether a user clicked the Submit button. If this is a post, IsPost returns true. This is the standard way in ASP.NET Web Pages to determine whether you're working with an initial request (a GET request) or a postback (a POST request). (For more information about GET and POST, see the sidebar "HTTP GET and POST and the IsPost Property" in Chapter 2: Introduction to Programming.)

    Next, you get the values that the user filled in from the Request object, and you put them in variables for later. The Request object contains all the values that were submitted with the page, each identified by a key. The key is the equivalent to the name attribute of the form field that you want to read. For example, to read the companyname field (text box), you use Request["companyname"].

    Form values are stored in the Request object as strings. Therefore, when you have to work with a value as a number or a date or some other type, you have to convert it from a string to that type. In the example, the AsInt method of the Request is used to convert the value of the employees field (which contains an employee count) to an integer.

  2. Launch the page in your browser, fill in the form fields, and click Submit. The page displays the values you entered.

    ch04_forms-3

Validating User Input

Users make mistakes. You ask them to fill in a field, and they forget to, or you ask them to enter the number of employees and they type a name instead. To make sure that a form has been filled in correctly before you process it, you validate the user's input.

This procedure shows how to validate all three form fields to make sure the user didn't leave them blank. You also check that the employee count value is a number. If there are errors, you'll display an error message that tells the user what values didn't pass validation.

  1. In the Form.cshtml file, replace the first block of code with the following code:

    @{
        if (IsPost)  {
            var errors = false;
            var companyname = Request["companyname"];
            if (companyname.IsEmpty()) {
                errors = true;
                @:Company name is required.<br />
            }
            var contactname = Request["contactname"];
            if (contactname.IsEmpty()) {
                errors = true;
                @:Contact name is required.<br />
            }
            var employeecount = 0;
            if (Request["employees"].IsInt()) {
                employeecount = Request["employees"].AsInt();
            } else {
                errors = true;
                @:Employee count must be a number.<br />
            }
            if (errors == false) {
                <text>
                  You entered: <br />
                  Company Name: @companyname <br />
                  Contact Name: @contactname <br />
                  Employee Count: @employeecount <br />
                </text>
            }    }
    }

    This code is similar to the code you replaced, but there are a few differences. The first difference is that it initializes a variable named errors to false. You'll set this variable to true if any validation tests fail.

    Each time the code reads the value of a form field, it performs a validation test. For the companyname and contactname fields, you validate them by calling the IsEmpty function. If the test fails (that is, if IsEmpty returns true) the code sets the errors variable to true and the appropriate error message is displayed.

    The next step is to make sure that the user entered a numeric value (an integer) for the employee count. To do this, you call the IsInt function. This function returns true if the value you're testing can be converted from a string to an integer. (Or of course false if the value can't be converted.) Remember that all values in the Request object are strings. Although in this example it doesn’t really matter, if you wanted to do math operations on the value, the value would have to be converted to a number.

    If IsInt tells you that the value is an integer, you set the employeecount variable to that value. However, before you do that, you have to actually convert it to an integer, because when employeecount was initialized, it was typed using int. Notice the pattern: the IsInt function tells you whether it's an integer; the AsInt function in the next line actually performs the conversion. If IsInt doesn't return true, the statements in the else block set the errors variable to true.

    Finally, after all the testing is done, the code determines whether the errors variable is still false. If it is, the code displays the text block that contains the values the user entered. Launch the page in your browser, leave the form fields blank, and click Submit. Errors are displayed.

    ch04_forms-4

  2. Enter values into the form fields and then click Submit. A page that shows the submitted values like you saw earlier is displayed.

Restoring Form Values After Postbacks

When you tested the page in the previous section, you might have noticed that if you had a validation error, everything you entered (not just the invalid data) was gone, and you had to re-enter values for all the fields. This illustrates an important point: when you submit a page, process it, and then render the page again, the page is re-created from scratch. As you saw, this means that any values that were in the page when it was submitted are lost.

You can fix this easily, however. You have access to the values that were submitted (in the Request object, so you can fill those values back into the form fields when the page is rendered.

  1. In the Form.cshtml file, replace the default page with the following markup:

    <!DOCTYPE html>
    <html>
        <head>
            <title>Customer Form</title>
        </head>
        <body>
          <form method="post" action="">
            <fieldset>
              <legend>Add Customer</legend>
              <div>
                <label for="CompanyName">Company Name:</label>
                <input type="text" name="CompanyName"
                       value="@Request["companyname"]" />
              </div>
              <div>
                <label for="ContactName">Contact Name:</label>
                <input type="text" name="ContactName"
                       value="@Request["contactname"]" />
              </div>
              <div>
                <label for="Employees">Employee Count:</label>
                <input type="text" name="Employees" value="@Request["employees"]" />
              </div>
              <div>
                <label> </label>
                <input type="submit" value="Submit" class="submit" />
              </div>
            </fieldset>
          </form>
        </body>
    </html>

    The value attribute of the <input> elements has been set to dynamically read the field value out of the Request object. The first time that the page is requested, the values in the Request object are all empty. This is fine, because that way the form is blank.

  2. Launch the page in your browser, fill in the form fields or leave them blank, and click Submit. A page that shows the submitted values is displayed.

    ch04_forms-5

Additional Resources

Microsoft ASP.NET Team

By Microsoft ASP.NET Team, ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.