10. Model Binding and Validation

Model binding automatically fills action parameters and model objects with values from the request: route values, query string and form fields. After binding, ModelState.IsValid tells you whether the data passed the validation rules from the model. Always check it before saving. Client-side validation gives instant feedback, but server-side validation is the one you must never skip.

Key points

  • Binding matches by name: an input called Name fills the Name property.
  • Sources: form body, route, query string. Use [FromQuery], [FromRoute] or [FromBody] to be specific.
  • Use [Bind] or a view model to prevent over-posting of fields the user should not set.
  • Add the validation scripts partial to show client-side messages.

Example: Binding from different sources

Controllers/StudentsController.cs
// /Students/Search?text=ana&page=2
public IActionResult Search(string text, int page = 1)
{
    ViewBag.Text = text;
    return View();
}

// /Students/Details/7
public IActionResult Details(int id)
{
    return View();
}
Show explanation

text and page come from the query string. id comes from the route. Missing values use the default or the type's default value.