liveBook · Manning

ModelState.AddModelError

As explained in ASP.NET Core in Action, 3e

AddModelError is a model-state operation that adds a validation error associated with a key or model field.

ModelState.AddModelError() adds an extra validation error when handler-level checks find a business-rule failure that DataAnnotation validation cannot detect. The error appears on the form alongside attribute-based errors. section 16.3.2

Use it during server-side validation

After checking a submitted value against application data or another system, call AddModelError() when the check fails. Then test ModelState.IsValid; if validation failed, return Page() so the form redisplays its errors instead of saving. 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");
    }
}

The handler pattern shows how ModelState.IsValid controls whether the form is redisplayed or successful processing continues. section 16.3.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains the purpose and handler flow, but does not provide a detailed AddModelError call or key-selection example.
Examples
Uses product existence checks and errors returned by a different system as examples of additional validation.
What it assumes
Assumes familiarity with Razor Pages handlers and ModelState.IsValid while distinguishing business checks from DataAnnotation checks.
What you can do after
Apply it via ModelState in a Razor Pages handler to redisplay invalid forms before saving.
How it connects
Connects ModelState.AddModelError with ModelState.IsValid, DataAnnotation validation, server-side validation, and business-rule validation.

Also explained in

Compare how 2 books explain ModelState.AddModelError →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.