Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to figure out which key of ModelState has error

How do I figure out which of the keys in ModelState that contains an error when ModelState.IsValid is false? Usually I would just hover the mouse thru the ModelState.Values list checking item by item for error count > 0. But now I'm working on a view that has some lists of complex objects, totalling 252 ModelState items(each item of each object of each list has an entry on ModelState.Keys).

So, is there an easier way to point out the error source?

like image 815
leobelones Avatar asked Mar 08 '13 14:03

leobelones


People also ask

How do I find my ModelState error?

You can use SelectMany function c# to get error message from modelstate mvc. It will generate error message string it contains modelstate errors; we can return as json and display in html element.

Which property is used to determine an error in ModelState?

Errors property and the ModelState. IsValid property. They're used for the second function of ModelState : to store the errors found in the submitted values.

What does ModelState IsValid mean?

ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process.


2 Answers

You can check the ViewData.ModelState.Values collection and see what are the Errors.

[Httpost]
public ActionResult Create(User model)
{
   if(ModelState.IsValid)
   {
     //Save and redirect
   }
   else
   {
     foreach (var modelStateVal in ViewData.ModelState.Values)
     {
       foreach (var error in modelStateVal.Errors)
       {               
          var errorMessage = error.ErrorMessage;
          var exception = error.Exception;
          // You may log the errors if you want
       }
     }
   }         
   return View(model);
 }
}

If you really want the Keys(the property name), You can iterate through the ModelState.Keys

foreach (var modelStateKey in ViewData.ModelState.Keys)
{
    var modelStateVal = ViewData.ModelState[modelStateKey];
    foreach (var error in modelStateVal.Errors)
    {
        var key = modelStateKey; 
        var errorMessage = error.ErrorMessage;
        var exception = error.Exception;
        // You may log the errors if you want
    }
}
like image 55
Shyju Avatar answered Sep 22 '22 07:09

Shyju


ModelState.Values.SelectMany(v => v.Errors);

is considered cleaner.

like image 30
IncaKola Avatar answered Sep 20 '22 07:09

IncaKola