James Ray Anderson

James Ray Anderson
James Ray Anderson
0 comments

Simple C# MVC ModelState Error List

10:00 PM

There are situations where you need to add an error to the state of the model. 

Add Error To Model
In these situations it is as easy as
ModelState.AddModelError("EmailAddress","Duplicate email.");



Model Errors
Then you may want to inspect the ModelState to determine if you have any errors before continuing processing. 
If (ModelState.IsValid == true)  { //Perform actions}
Specific Model Error
But what if you just want to inspect a particular error to perform another action?
int errorCount = ModelState["EmailAddr"].Errors;
List of Model Errors
You can also get a list of errors from the model
List<ModelError> modelErrorList = ModelState.Keys.SelectMany(x => this.ModelState[x].Errors).ToList();
 
Toggle Footer
Top