ModelState is the ASP.NET Core request-state dictionary that stores bound values and validation errors associated with properties or the model. On a Razor Page, the PageModel exposes it as a ModelStateDictionary. Use ModelState.IsValid to check whether bound properties and parameters are valid before running business logic. section 15.3 section 16.3.2
Model binding and validation happen before a page handler executes, but the handler runs whether validation succeeds or fails. The handler is responsible for checking the result and deciding what to return. section 16.3.2
Listing 16.7 Checking model state to view the validation result
public class CheckoutModel : PageModel #1
{
[BindProperty] #2
public UserBindingModel Input { get; set; } #2
public IActionResult OnPost() #3
{
if (!ModelState.IsValid) #4
{
return Page(); #5
}
/* Save to the database, update user, return success */ #6
return RedirectToPage("Success");
}
}
This checkout handler checks ModelState.IsValid first. On failure, Page() redisplays the form with the supplied values and validation messages. On success, the handler redirects to the success page. section 16.3.2
A redirect after a successful POST follows the POST-REDIRECT-GET pattern. For invalid input, returning the page instead lets the user correct the form. Validation attribute messages can be customized, for example with [Required(ErrorMessage="Required")]. section 16.3.2
For web APIs, invalid model state commonly results in a 400 Bad Request with validation errors. The [ApiController] attribute normally supplies this behavior automatically, using Problem Details responses. If you cannot or do not want to use it, an action filter can check model state and short-circuit the action. section 22.1.3
Listing 22.5 The action filter for validating ModelState
public class ValidateModelAttribute : ActionFilterAttribute #1
{
public override void OnActionExecuting( #2
ActionExecutingContext context) #2
{
if (!context.ModelState.IsValid) #3
{
context.Result = #4
new BadRequestObjectResult(context.ModelState); #4
}
}
}
This action filter checks context.ModelState.IsValid before the action runs and sets a BadRequestObjectResult containing the model state when validation fails. section 22.1.3
When unit-testing a controller or page handler directly, model binding does not run, so ModelState is not populated from the supplied model. Add an error manually with controller.ModelState.AddModelError before calling the action to test its invalid-state path. Keep the test model consistent with the error so the test represents a realistic request. section 36.2
Filters can access MVC constructs such as ModelState; general middleware works at a lower level and cannot use them. Consider a filter when a shared check needs ModelState across selected MVC actions or Razor Pages. section 21.3


