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
Request
object.- Input validation.
- HTML encoding.
Software versions used in the tutorial
- ASP.NET Web Pages (Razor) 3
This tutorial also works with ASP.NET Web Pages 2.
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:
[!code-htmlMain]1: <!DOCTYPE html>
2: <html>
3: <head>
4: <title>Customer Form</title>
5: </head>
6: <body>
7: <form method="post" >
8: <fieldset>
9: <legend>Add Customer</legend>
10: <div>
11: <label for="CompanyName">Company Name:</label>
12: <input type="text" name="CompanyName" value="" />
13: </div>
14: <div>
15: <label for="ContactName">Contact Name:</label>
16: <input type="text" name="ContactName" value="" />
17: </div>
18: <div>
19: <label for="Employees">Employee Count:</label>
20: <input type="text" name="Employees" value="" />
21: </div>
22: <div>
23: <label> </label>
24: <input type="submit" value="Submit" class="submit" />
25: </div>
26: </fieldset>
27: </form>
28: </body>
29: </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:
[!code-cshtmlMain]
1: @{
2: if (IsPost) {
3: string companyname = Request.Form["companyname"];
4: string contactname = Request.Form["contactname"];
5: int employeecount = Request.Form["employees"].AsInt();
6:
7: <text>
8: You entered: <br />
9: Company Name: @companyname <br />
10: Contact Name: @contactname <br />
11: Employee Count: @employeecount <br />
12: </text>
13: }
14: }
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
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 Introduction to ASP.NET Web Pages Programming Using the Razor Syntax.)Next, you get the values that the user filled in from the
Form values are stored in theRequest.Form
object, and you put them in variables for later. TheRequest.Form
object contains all the values that were submitted with the page, each identified by a key. The key is the equivalent to thename
attribute of the form field that you want to read. For example, to read thecompanyname
field (text box), you useRequest.Form["companyname"]
.Request.Form
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, theAsInt
method of theRequest.Form
is 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.
[!TIP]
### HTML Encoding for Appearance and Security
HTML has special uses for characters like
<
,>
, and&
. If these special characters appear where they’re not expected, they can ruin the appearance and functionality of your web page. For example, the browser interprets the<
character (unless it’s followed by a space) as the beginning of an HTML element, like<b>
or<input ...>
. If the browser doesn’t recognize the element, it simply discards the string that begins with<
until it reaches something that it again recognizes. Obviously, this can result in some weird rendering in the page.HTML encoding replaces these reserved characters with a code that browsers interpret as the correct symbol. For example, the
<
character is replaced with<
and the>
character is replaced with>
. The browser renders these replacement strings as the characters that you want to see.It’s a good idea to use HTML encoding any time you display strings (input) that you got from a user. If you don’t, a user can try to get your web page to run a malicious script or do something else that compromises your site security or that’s just not what you intend. (This is particularly important if you take user input, store it someplace, and then display it later — for example, as a blog comment, user review, or something like that.)
To help prevent these problems, ASP.NET Web Pages automatically HTML-encodes any text content that you output from your code. For example, when you display the content of a variable or an expression using code such as
@MyVar
, ASP.NET Web Pages automatically encodes the output.
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.
In the Form.cshtml file, replace the first block of code with the following code:
[!code-cshtmlMain]
1: @{
2: Validation.RequireField("companyname", "Company name is required.");
3: Validation.RequireField("contactname", "Contact name is required.");
4: Validation.RequireField("employees", "Employee count is required.");
5: Validation.Add("employees", Validator.Integer());
6:
7: if (IsPost) {
8: var companyname = Request.Form["companyname"];
9: var contactname = Request.Form["contactname"];
10: var employeecount = Request.Form["employees"];
11: if(Validation.IsValid()){
12: <text>
13: You entered: <br />
14: Company Name: @companyname <br />
15: Contact Name: @contactname <br />
16: Employee Count: @employeecount <br />
17: </text>
18: }
19: }
20: }
To validate user input, you use the
When the page runs, ASP.NET does all the validation for you. You can check the results by callingValidation
helper. You register required fields by callingValidation.RequireField
. You register other types of validation by callingValidation.Add
and specifying the field to validate and the type of validation to perform.Validation.IsValid
, which returns true if everything passed and false if any field failed validation. Typically, you callValidation.IsValid
before you perform any processing on the user input.Update the
<body>
element by adding three calls to theHtml.ValidationMessage
method, like this:[!code-cshtmlMain]
1: <body>
2: <form method="post">
3: <fieldset>
4: <legend>Add Customer</legend>
5: <div>
6: <label for="CompanyName">Company Name:</label>
7: <input type="text" name="CompanyName" value="" />
8: @Html.ValidationMessage("companyname")
9: </div>
10: <div>
11: <label for="ContactName">Contact Name:</label>
12: <input type="text" name="ContactName" value="" />
13: @Html.ValidationMessage("contactname")
14: </div>
15: <div>
16: <label for="Employees">Employee Count:</label>
17: <input type="text" name="Employees" value="" />
18: @Html.ValidationMessage("employees")
19: </div>
20: <div>
21: <label> </label>
22: <input type="submit" value="Submit" class="submit" />
23: </div>
24: </fieldset>
25: </form>
26: </body>
ValidationMessage
and pass it the name of the field that you want the message for.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.
ASP.NET Web Pages 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.
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
value
attributes of the<input>
elements using thevalue
attribute.:[!code-cshtmlMain]
1: <!DOCTYPE html>
2: <html>
3: <head>
4: <title>Customer Form</title>
5: </head>
6: <body>
7: <form method="post">
8: <fieldset>
9: <legend>Add Customer</legend>
10: <div>
11: <label for="CompanyName">Company Name:</label>
12: <input type="text" name="CompanyName"
13: value="@Request.Form["companyname"]" />
14: @Html.ValidationMessage("companyname")
15: </div>
16: <div>
17: <label for="ContactName">Contact Name:</label>
18: <input type="text" name="ContactName"
19: value="@Request.Form["contactname"]" />
20: @Html.ValidationMessage("contactname")
21: </div>
22: <div>
23: <label for="Employees">Employee Count:</label>
24: <input type="text" name="Employees"
25: value="@Request.Form["employees"]" />
26: @Html.ValidationMessage("employees")
27: </div>
28: <div>
29: <label> </label>
30: <input type="submit" value="Submit" class="submit" />
31: </div>
32: </fieldset>
33: </form>
34: </body>
value
attribute of the<input>
elements has been set to dynamically read the field value out of theRequest.Form
object. The first time that the page is requested, the values in theRequest.Form
object 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.
- 1,001 Ways to Get Input from Web Users
- Using Forms and Processing User Input
- Validating User Input in ASP.NET Web Pages Sites
- Using AutoComplete in HTML Forms
|