Programmer's Picnic · Learn With Champak
Razor course · Lesson 4 of 4

Forms, binding and POST

Read the explanation, run the sample, and try the exercise.

Pages/Hello.cshtml.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.ComponentModel.DataAnnotations;
namespace PicnicRazor.Pages;
public class HelloModel : PageModel
{
    [BindProperty, Required, StringLength(40)]
    public string Name { get; set; } = "";
    public string Greeting { get; private set; } = "";
    public void OnPost()
    {
        if (ModelState.IsValid) Greeting = $"Hello, {Name}!";
    }
}

Pages/Hello.cshtml

@page
@model PicnicRazor.Pages.HelloModel
<h1>Say hello</h1>
<form method="post">
    <label asp-for="Name"></label>
    <input asp-for="Name" />
    <span asp-validation-for="Name"></span>
    <button type="submit">Greet</button>
</form>
<p>@Model.Greeting</p>

Practice and security

Keep the generated _ViewImports.cshtml and Tag Helpers; Razor Pages includes antiforgery protections for forms. Try submitting an empty name, then a valid name. Server-side validation is essential.

← PreviousIndex →