ASP.NET Tutorial menu

ASP.NET Forms and Validation

Forms let visitors send data to your app. Razor Pages make reading and checking that data easy.

A Model Class

First describe the data the form collects. Attributes like [Required] add validation rules:

Example

csharp
using System.ComponentModel.DataAnnotations;

namespace SchoolSite.Models;

public class Admission
{
    [Required, StringLength(50)]
    public string Name { get; set; } = "";

    [Required, EmailAddress]
    public string Email { get; set; } = "";

    [Range(14, 60, ErrorMessage = "Age must be between 14 and 60.")]
    public int Age { get; set; }

    [Required]
    public string Course { get; set; } = "";
}

Common Validation Attributes

AttributeRule
[Required]The field cannot be empty
[StringLength(50)]Maximum length of text
[EmailAddress]Must look like an email
[Phone]Must look like a phone number
[Range(1, 100)]Number between two values
[Compare("Password")]Must match another field

The PageModel

Example

csharp
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using SchoolSite.Models;

namespace SchoolSite.Pages;

public class ApplyModel : PageModel
{
    [BindProperty]
    public Admission Input { get; set; } = new();

    public void OnGet() { }

    public IActionResult OnPost()
    {
        if (!ModelState.IsValid)
        {
            return Page();   // show the form again with errors
        }

        // Save Input to a database here
        TempData["Message"] = $"Thank you {Input.Name}, your form was received.";
        return RedirectToPage("/Thanks");
    }
}
  • [BindProperty] fills Input from the posted form fields automatically. This is model binding.
  • OnPost() runs when the form is submitted.
  • ModelState.IsValid is false if any validation rule failed.

The Form Page

Tag helpers like asp-for connect each input to a property. They set the name, the type and the validation attributes for you.

Example

cshtml
@page
@model SchoolSite.Pages.ApplyModel

<h1>Apply for Admission</h1>

<form method="post">
    <div asp-validation-summary="ModelOnly"></div>

    <label asp-for="Input.Name"></label>
    <input asp-for="Input.Name" />
    <span asp-validation-for="Input.Name"></span>

    <label asp-for="Input.Email"></label>
    <input asp-for="Input.Email" />
    <span asp-validation-for="Input.Email"></span>

    <label asp-for="Input.Age"></label>
    <input asp-for="Input.Age" />
    <span asp-validation-for="Input.Age"></span>

    <select asp-for="Input.Course">
        <option value="">Choose a course</option>
        <option>Web Development</option>
        <option>Graphic Designing</option>
    </select>
    <span asp-validation-for="Input.Course"></span>

    <button type="submit">Submit</button>
</form>

If a visitor submits the form with an empty name and age 10, the page comes back showing:

Output
The Name field is required.
Age must be between 14 and 60.

Always check ModelState.IsValid on the server. Browser-side checks are only for convenience, because anyone can skip them.

Post-Redirect-Get

After a successful post, redirect to another page instead of returning the same page. If the user then presses refresh, the browser will not send the form a second time. That is why the example uses RedirectToPage("/Thanks").

The thank-you page can show the message saved in TempData:

Example

cshtml
@page
<h1>Thank You</h1>
<p>@TempData["Message"]</p>
Output
Thank You
Thank you Ali, your form was received.

Built-in Protection

Razor Pages forms include a hidden anti-forgery token automatically. It stops other websites from secretly posting forms to your app (a CSRF attack). You do not need to add anything yourself.

Exercise

Exercise

What does ModelState.IsValid tell you in OnPost()?

Learn ASP.NET with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp