ASP.NET Core Interview Question #117

What is ModelState?

Routing, Controllers & Model Binding Mid-Level Intermediate

Quick Interview Answer

ModelState stores information about model binding and model validation for the current request. It contains attempted values and any binding or validation errors.

Detailed Explanation

ModelState stores information about model binding and model validation for the current request. It contains attempted values and any binding or validation errors.

In MVC form processing, an action commonly checks ModelState.IsValid before performing the operation. If validation fails, the same view can be returned with the submitted model so validation messages can be displayed.

With controllers using ApiController behavior, invalid model state can automatically produce an HTTP 400 response unless that behavior is customized.

Code Example

[HttpPost]
public IActionResult Create(CreateProductViewModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    _service.Create(model);
    return RedirectToAction(nameof(Index));
}