ASP.NET Web Pages - Forms

Forms allow users to submit data to your website, and it can be a simple form such as a contact form. In ASP.NET Web Pages, building forms is quite simple and clean, similar to PHP.

  1. Create an empty website in WebMatrix and name it Forms
  2. In the root directory create a file called Forms.cshtml

When retrieving data from HTML elements we use the Request object. This gets the value of the HTML elements when the form is submitted.

Syntax

Request.Form[“element name”]

You can also use the short-hand method, which is what this example will use throughout.

Request[“element name”]

Example

In the Forms.cshtml copy this code:

@{

var msg = "";

if (IsPost)
{

   var FirstName = Request["FirstName"];
   var LastName = Request["LastName"];

   msg = "Welcome " + FirstName + " " + LastName;
}

}

This is the code which will process the data. Firstly we made 1 variable above the If Statement named  msg. Then we have if (IsPost), which simply means on form submit process the data. The two variables FirstName and LastName have been set to get the values from the HTML elements, and the msg has a new value which is a simple welcome message.

The reason why the msg variable was created outside of the If Statement is because if it was created inside the If Statement it would be a local variable. Therefore it would not be possible to use it outside of the If Statement. It is completely fine to create variables inside the If Statement but remember they will be local and not global; here the FirstName and LastName variables are local to the If Statement and cannot be used outside.

HTML

<!DOCTYPE html>
 
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        @msg
 
        <form method="post">
        <input type="text" placeholder="First Name" name="FirstName"/>
        <input type="text" placeholder="Last Name" name="LastName"/>
 
        <input type="submit"/>
 
        </form>
 
    </body>
</html>

The input elements must be in a <form> tag with the method post or it will not work, and you must specify the name attribute so when the form is submitted ASP.NET can retrieve the value of the element.

The msg you see above the form tag will output our message when the form has been submitted.

Validation

As you can see with a small amount code you have managed to create a simple form. However, forms are not always simple and many more complicated forms include validation an important part of security when getting user data. In the next example we will work with the same code but expand it a little and make sure the data is valid before allowing the data to be sent off.

ASP.NET Web Pages 2 provides a new class with advanced validation. The previous version had the ModelState class which can still be used, but for this tutorial we will focus on the Validation class.

In the Form.cshtml replace the existing code with:

@{
 
var msg = "";

Validation.Add("FirstName", 
Validator.Required("This field is required"),
Validator.StringLength(10, 3, "Name must be greater than 3 characters but less than 10")
 
);
 
Validation.Add("LastName", 
Validator.Required("This field is required"),
Validator.StringLength(10, 3, "Name must be greater than 3 characters but less than 10")
 
);
 
if (IsPost)
{
   var FirstName = Request["FirstName"];
   var LastName = Request["LastName"];
   
   if (Validation.IsValid())
   {
       msg = "Welcome " + FirstName + " " + LastName;
   }else{
       Validation.AddFormError("Sorry there were errors in your submission");
   }
}

}

The difference here is the Validation.Add. The Add method of the Validation class accepts two arguments (string field, param Validators). The validators class has some methods you can use to make sure the data is valid. Here we outline a few:

  • DateTime
  • Integer
  • Decimal
  • Float
  • URL
  • Required
  • StringLength
  • Regex

These methods will make sure the data entered is correct. The regex method allows you to enter a custom expression. Unfortunately there is no email method.

When the user submits the data the Validation.IsValid checks to see if the data entered was correct; if not it will flag an error.

HTML

<!DOCTYPE html>
 
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        @msg
        @Html.ValidationSummary(true)
 
        <form method="post">
        <input type="text" placeholder="First Name" name="FirstName"/>
            @Html.ValidationMessage("firstname")
        <input type="text" placeholder="Last Name" name="LastName"/>
            @Html.ValidationMessage("firstname")
 
            <input type="submit"/>
 
        </form>
 
    </body>
</html>

The difference here is ValidationSummary and ValidationMessage. The ValidationMessage outputs the error message for the HTML element, and the ValidationSummary displays the AddForm error message.

Passing Data Between Pages

The examples you seen so far are all based on one page. These pages can get quite long, and you may want the C# code on one page and HTML on another. In this case you can pass the data onto another page to handle. To do this in the <form> tag we use the action attribute.

Create a new file in the root directory called Food.cshtml and another file called Food_Handler.cshtml.

In the Food.cshtml insert the following HTML:

<!DOCTYPE html>
 
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <form method="get" action="/Food_Handler.cshtml">
 
            <fieldset>
 
                <p>Please select your favourite food:</p>
 
                  Pizza:<input type="checkbox" value="Pizza" name="Food"/>
                  Paste:<input type="checkbox" value="Pasta" name="Food"/>
                  Chicken:<input type="checkbox" value="Chicken" name="Food"/>
 
                 <p>Please select your favourite drink:</p>
 
                  Coke:<input type="radio" value="Coke" name="drinks"/>
                  Sprite:<input type="radio" value="Sprite" name="drinks"/>
                  Lemonade:<input type="radio" value="Lemonade" name="drinks"/>
                <input type="submit"/>

            </fieldset>

        </form>
    </body>
</html>

Here we are using the get method instead of post. The post method does not show the result in the URL, but the get method does; this is known as a querystring.

We are also using checkboxes and radio buttons in order to show you  that the checkboxes and radio buttons must be provided the value attribute.

In the Food_Handler.cshtml insert:

@{
var food = Request["food"];
var drinks = Request["drinks"];  
}

@food @drinks

You will notice that we do not use if(IsPost) because the data was sent from an external page and was posted from there. If you try it, the URL will look like:

Food_Handler.cshtml?Food=Pasta&Food=Chicken&drinks=Sprite (The part in bold is known as a querystring)

This time the data was retrieved from the URL. If you wanted to validate the data you’d have to do that on the Food.cshtml page.

Try it!

Name:

Age:

Favourite Colour:

Summary

This tutorial covered how to create forms in ASP.NET Web Pages, as well as validating user data. It is very simple to create basic and complex forms, just remember to always validate the user input.