Introduction
Model binding is the magic that turns HTTP form fields into C# objects. Combined with validation and anti-forgery tokens, it powers ShopNest user registration and login safely.
After this article you will
- Build forms with Tag Helpers and model binding
- Use [FromForm], [FromQuery], [FromRoute], [FromBody]
- Enable client-side jQuery unobtrusive validation
- Protect forms with anti-forgery tokens
Prerequisites
- Article 9 — Models and ViewModels
- ShopNest.Web project from prior lessons
Concept deep-dive
When a form posts, the model binder walks the request: form fields → properties by name match. Nested objects use dot notation: Address.City. Collections use indexed names: Phones[0].Number.
<form asp-action="Register" method="post">
@Html.AntiForgeryToken()
<input asp-for="Email" />
<span asp-validation-for="Email"></span>
<div asp-validation-summary="ModelOnly"></div>
</form>
Enable client validation in _Layout: jquery.validate + jquery.validate.unobtrusive. Custom rules: inherit ValidationAttribute.
Hands-on — ShopNest User Registration Form
- RegisterViewModel with password confirm custom validation.
- GET shows form; POST validates and creates user (stub).
- Display validation summary and field errors.
- Verify __RequestVerificationToken in request (DevTools).
Common errors & best practices
- Binding fails silently — check property names match input name attributes.
- CSRF: always [ValidateAntiForgeryToken] on POST mutating actions.
- Complex types need [FromForm] when mixing sources.
Interview questions
Q: How does model binding work?
A: Value providers read route/query/form/body; binder sets action parameters and ModelState.
Q: What is anti-forgery?
A: Synchronizer token pattern — hidden field + cookie validated on POST.
Summary
- Model binding maps HTTP data to C# automatically
- Validate with Data Annotations + ModelState
- Anti-forgery prevents CSRF on registration forms
Previous: Models and ViewModels
Next: Tag Helpers
FAQ
Can I bind JSON body to MVC action?
Yes with [FromBody] — more common in API controllers.
Why ModelOnly validation summary?
Hides field-level errors already shown next to inputs; shows cross-field errors.