Find out Model State Error


Sometime we got stuck at some model error in MVC controller, in result ModelState.IsValid
always return false, so in this case below code snippet is useful to find out error in Model state.


var errors = ModelState.Values.SelectMany(v => v.Errors);
foreach (var error in errors)
 {
    //DoSomethingWith(error);

 }


     OR

if(!ModelState.IsValid)
{
    foreach (ModelState modelState in ViewData.ModelState.Values)
    {
      foreach (ModelError error in modelState.Errors)
      {
      //DoSomethingWith(error);
      }
    }
}

Comments