Model Binding & Validation
Model binding = ASP.NET fills your action parameters from HTTP request. Validation = check if data is valid.
60-Second Version: Binding = auto-fill parameters from URL, form, or JSON. Validation =
ModelState.IsValid. If false, return View with errors.1. Binding Sources: Where Data Comes From
Request: POST /product/create with form data Name=Phone&Price=999
[HttpPost]
public IActionResult Create(ProductCreateViewModel vm)
{
// vm.Name = "Phone" โ auto-filled from form
// vm.Price = 999 โ auto-filled + converted to decimal
}
Order: 1. Form values 2. Route values 3. Query string 4. Body. First match wins.
2. Explicit Binding Attributes
| Attribute | Binds From | Example |
|---|---|---|
[FromForm] | Form post | <input name="Name"> |
[FromRoute] | URL segment | /edit/5 โ int id |
[FromQuery] | ?key=value | ?page=2 โ int page |
[FromBody] | JSON body | API: {"name":"Phone"} |
[FromHeader] | HTTP header | X-Api-Key: xyz |
Rule: MVC defaults to Form. API with [ApiController] defaults to Body.
3. Validation: Data Annotations
public class ProductCreateViewModel
{
[Required(ErrorMessage = "Name required")]
[StringLength(100, MinimumLength = 3)]
public string Name { get; set; }
[Range(1, 10000)]
public decimal Price { get; set; }
[EmailAddress]
public string ContactEmail { get; set; }
}
Controller check:
[HttpPost]
public IActionResult Create(ProductCreateViewModel vm)
{
if (!ModelState.IsValid)
{
return View(vm); // Returns to form with errors
}
// Save to DB
return RedirectToAction("Index");
}
4. Show Errors in View
<form asp-action="Create">
<div asp-validation-summary="All" class="text-danger"></div>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
<input asp-for="Price" class="form-control" />
<span asp-validation-for="Price" class="text-danger"></span>
<button type="submit">Save</button>
</form>
asp-validation-for shows error for one field. asp-validation-summary shows all.
Beginner Trap: Neha forgets
if (!ModelState.IsValid). Saves invalid data to DB. Or returns View() without model โ form fields blank, user re-types everything. Fix: return View(vm);
Quick Check ๐ง
Next: Filters & Middleware in MVC - Action filters, exception filters, and pipeline.
No comments yet. Be the first to share your thoughts!