Course contentsShow
← C#
Lesson 1304 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Form Handling and Model Binding

Capture user input from HTML forms using automatic model binding in Razor pages.

In this lesson, you will learn how to bridge the gap between user input in HTML forms and your C# code using the power of automatic model binding in Razor Pages.

Beyond Manual Data Extraction

In traditional web development, handling a form required manually parsing a request object, grabbing string values by name, and converting them into C# types. In Razor Pages, we simplify this drastically through Model Binding. This is the process where the framework automatically maps incoming HTTP form fields (like <input name="Email">) directly to properties on your page model.

The Mechanics of Binding

To enable this, you define a class or properties within your PageModel and use the [BindProperty] attribute. When a user submits a POST request, the framework inspects the names of the input fields and matches them to your properties.

Consider this example in your PageModel (Index.cshtml.cs):

public class ContactModel : PageModel
{
    [BindProperty]
    public string UserName { get; set; }

    [BindProperty]
    public int Age { get; set; }

    public IActionResult OnPost()
    {
        // The data is already mapped to the properties!
        if (ModelState.IsValid)
        {
            // Process UserName and Age here
        }
        return Page();
    }
}

In your Razor markup (Index.cshtml), ensure your form inputs match these property names:

<form method="post">
    <input asp-for="UserName" />
    <input asp-for="Age" />
    <button type="submit">Submit</button>
</form>

Why This Matters

When you use asp-for tag helpers, the framework generates the name attribute for you, ensuring that the HTML matches your C# model exactly. By the time your OnPost method executes, you don't have to worry about fetching form values; the data is already waiting for you in your properties. This reduces boilerplate code and prevents errors associated with manual data mapping and type conversion. The framework even handles basic validation parsing for you automatically.

Key Takeaway: Model binding eliminates the need for manual form parsing by automatically synchronizing HTML input values with your C# PageModel properties using the [BindProperty] attribute.