liveBook · Manning

ModelState.AddModelError

As explained in Pro ASP.NET Core 7, Tenth Edition

AddModelError is an ASP.NET Core MVC ModelState operation that adds a validation error associated with a model key.

ModelState.AddModelError records a validation error during ASP.NET Core MVC request processing. Give it a model key and a message; the key associates the error with a property, while an empty key records an error for the entire model. section 29.3.3 section 29.3.5

Use the operation when validation depends on information that model attributes cannot express:

  • Check the relevant ModelState validation state before performing custom validation, avoiding duplicate or conflicting messages when binding already failed. section 29.3.3
  • Pass a property name such as nameof(Product.Price) to attach a message to that field; the message can then appear beside the input. section 29.3.3
  • Pass an empty string when the rule concerns several properties, such as a product name and price combination. section 29.3.5
  • Check ModelState.IsValid afterward so implicit binding errors and explicit errors follow the same submission path. section 29.3.3

Property and model-level errors

In a POST action, add a property error when a successfully bound price is not positive: ModelState.AddModelError(nameof(Product.Price), "Enter a positive price"). For a rule stating that products whose names start with "Small" cannot exceed $100, use ModelState.AddModelError("", "Small products cannot cost more than $100"). Configure asp-validation-summary="ModelOnly" when the summary should display only the latter category.

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Explains property and model-level keys, validation-state checks, display configuration, and controller tests without covering framework internals.
Examples
Uses positive-price validation, database-backed identifier checks, cross-property product rules, and empty-cart checkout validation.
What it assumes
Assumes familiarity with MVC model binding and validation attributes while demonstrating how ModelState carries their results.
What you can do after
Apply it via ASP.NET Core MVC controllers to reject invalid submissions and redisplay actionable errors.
How it connects
Connects model binding, model validation, ModelState.IsValid, validation summaries, and controller testing.

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 Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.