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.

