ASP.NET Core MVC Interview Question #37
What is ModelState in ASP.NET Core MVC?
Controllers, Actions, Model Binding & Action Results Junior Beginner
Quick Interview Answer
ModelState contains the results of model binding and model validation for the current request. It stores attempted values and validation errors associated with fields.
Detailed Explanation
ModelState contains the results of model binding and model validation for the current request. It stores attempted values and validation errors associated with fields.
A POST action commonly checks ModelState.IsValid before performing a state-changing operation. If validation fails, returning the same view allows Razor validation helpers or Tag Helpers to display the recorded errors.
Code Example
[HttpPost]
public IActionResult Create(ProductEditViewModel model)
{
if (!ModelState.IsValid)
return View(model);
// Save valid input.
return RedirectToAction(nameof(Index));
}