Working with HTML Forms in ASP.NET Web Pages (Razor) Sites
This article describes how to process an HTML form (with text boxes and buttons) when you are working in an ASP.NET Web Pages (Razor) website.
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 article:
- The
Requestobject. - Input validation.
- HTML encoding.
Note The information in this article applies to ASP.NET Web Pages 1.0 and Web Pages 2. Where there are differences between versions, the text describes the differences.
Creating a Simple HTML Form
-
Create a new website.
-
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" > <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>
-
Launch the page in your browser. (In WebMatrix, in the Files workspace, right-click the file and then select Launch in browser.) A simple form with three input fields and a Submit button is displayed.

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 article about working with databases.)
-
At the top of the Form.cshtml file, enter the following code:
@{ if (IsPost) { string companyname = Request.Form["companyname"]; string contactname = Request.Form["contactname"]; int employeecount = Request.Form["employees"].AsInt(); <text> You entered: <br /> Company Name: @companyname <br /> Contact Name: @contactname <br /> Employee Count: @employeecount <br /> </text> } }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. By default, the request goes to the same page (namely, Form.cshtml).
When you submit the page this time, the values you entered are displayed just above the form:

Look at the code for the page. You first use the
IsPostmethod to determine whether the page is being posted — that is, whether a user clicked the Submit button. If this is a post,IsPostreturns 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 Introduction to ASP.NET Web Pages Programming Using the Razor Syntax.)Next, you get the values that the user filled in from the
Request.Formobject, and you put them in variables for later. TheRequest.Formobject contains all the values that were submitted with the page, each identified by a key. The key is the equivalent to thenameattribute of the form field that you want to read. For example, to read thecompanynamefield (text box), you useRequest.Form["companyname"].Form values are stored in the
Request.Formobject 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, theAsIntmethod of theRequest.Formis used to convert the value of the employees field (which contains an employee count) to an integer. -
Launch the page in your browser, fill in the form fields, and click Submit. The page displays the values you entered.
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.
To validate input in ASP.NET Web Pages 2
This procedure shows the basics of validating user input if you're using ASP.NET Web Pages 2. If you're using ASP.NET Web Pages 1.0, skip this section and go to To validate input in ASP.NET Web Pages 1.0 below.
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.
- In the Form.cshtml file, replace the first block of code with the following code:
@{ Validation.RequireField("companyname", "Company name is required."); Validation.RequireField("contactname", "Contact name is required."); Validation.RequireField("employees", "Employee count is required."); Validation.Add("employees", Validator.Integer()); if (IsPost) { var companyname = Request.Form["companyname"]; var contactname = Request.Form["contactname"]; var employeecount = Request.Form["employees"]; if(Validation.IsValid()){ <text> You entered: <br /> Company Name: @companyname <br /> Contact Name: @contactname <br /> Employee Count: @employeecount <br /> </text> } } }To validate user input, you use the
Validationhelper. You register required fields by callingValidation.RequireField. You register other types of validation by callingValidation.Addand specifying the field to validate and the type of validation to perform.When the page runs, ASP.NET does all the validation for you. You can check the results by calling
Validation.IsValid, which returns true if everything passed and false if any field failed validation. Typically, you callValidation.IsValidbefore you perform any processing on the user input. Update the
<body>element by adding three calls to theHtml.ValidationMessagemethod, like this:<body> <form method="post"> <fieldset> <legend>Add Customer</legend> <div> <label for="CompanyName">Company Name:</label> <input type="text" name="CompanyName" value="" /> @Html.ValidationMessage("companyname") </div> <div> <label for="ContactName">Contact Name:</label> <input type="text" name="ContactName" value="" /> @Html.ValidationMessage("contactname") </div> <div> <label for="Employees">Employee Count:</label> <input type="text" name="Employees" value="" /> @Html.ValidationMessage("employees") </div> <div> <label> </label> <input type="submit" value="Submit" class="submit" /> </div> </fieldset> </form> </body>Run the page. Leave the fields blank and click Submit. You see error messages.

Add a string (for example, "ABC") to the Employee Count field and click Submit again. This time you see an error that indicates that the string isn't in the right format, namely, an integer.

To display validation error messages, you can call Html.ValidationMessage
and pass it the name of the field that you want the message for.
ASP.NET Web Pages 2 provides more options for validating user input, including the ability to automatically perform validation using client script, so that users get immediate feedback in the browser. See the Additional Resources section later for more information.
To validate input in ASP.NET Web Pages 1.0
This procedure shows the process for validating user input if you're using ASP.NET Web Pages 1.0. If you're using ASP.NET Web Pages 2, you can use this procedure, but there's a more convenient way to validate user input -- see To validate input in ASP.NET Web Pages 2 earlier.
The 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.
-
In the Form.cshtml file, replace the first block of code with the following code:
@{ if (IsPost) { var errors = false; var companyname = Request.Form["companyname"]; if (companyname.IsEmpty()) { errors = true; @:Company name is required.<br /> } var contactname = Request.Form["contactname"]; if (contactname.IsEmpty()) { errors = true; @:Contact name is required.<br /> } var employeecount = 0; if (Request.Form["employees"].IsInt()) { employeecount = Request.Form["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
errorsto 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
companynameandcontactnamefields, you validate them by calling theIsEmptyfunction. If the test fails (that is, ifIsEmptyreturns 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
IsIntfunction. 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 b be converted.) Remember that all values in theRequest.Formobject 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
IsInttells you that the value is an integer, you set theemployeecountvariable to that value. However, before you do that, you have to actually convert it to an integer, because whenemployeecountwas initialized, it was typed usingint. Notice the pattern: theIsIntfunction tells you whether it's an integer; theAsIntfunction in the next line actually performs the conversion. IfIsIntdoesn't return true, the statements in theelseblock set theerrorsvariable to true.Finally, after all the testing is done, the code determines whether the
errorsvariable 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.
-
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.Form object, so you can fill those values back into the form fields when the page is rendered.
-
In the Form.cshtml file, replace the
valueattributes of the<input>elements using thevalueattribute. Here's the version for ASP.NET Web Pages 2:<!DOCTYPE html> <html> <head> <title>Customer Form</title> </head> <body> <form method="post"> <fieldset> <legend>Add Customer</legend> <div> <label for="CompanyName">Company Name:</label> <input type="text" name="CompanyName" value="@Request.Form["companyname"]" /> @Html.ValidationMessage("companyname") </div> <div> <label for="ContactName">Contact Name:</label> <input type="text" name="ContactName" value="@Request.Form["contactname"]" /> @Html.ValidationMessage("contactname") </div> <div> <label for="Employees">Employee Count:</label> <input type="text" name="Employees" value="@Request.Form["employees"]" /> @Html.ValidationMessage("employees") </div> <div> <label> </label> <input type="submit" value="Submit" class="submit" /> </div> </fieldset> </form> </body>And here's the version for ASP.NET Web Pages 1.0:
<!DOCTYPE html> <html> <head> <title>Customer Form</title> </head> <body> <form method="post"> <fieldset> <legend>Add Customer</legend> <div> <label for="CompanyName">Company Name:</label> <input type="text" name="CompanyName" value="@Request.Form["companyname"]" /> </div> <div> <label for="ContactName">Contact Name:</label> <input type="text" name="ContactName" value="@Request.Form["contactname"]" /> </div> <div> <label for="Employees">Employee Count:</label> <input type="text" name="Employees" value="@Request.Form["employees"]" /> </div> <div> <label> </label> <input type="submit" value="Submit" class="submit" /> </div> </fieldset> </form> </body> </html>
The
valueattribute of the<input>elements has been set to dynamically read the field value out of theRequest.Formobject. The first time that the page is requested, the values in theRequest.Formobject are all empty. This is fine, because that way the form is blank. -
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.


Comments (0) RSS Feed