How do you get a list of all ModelState error messages? I found this code to get all the keys: ( Returning a list of keys with ModelState errors)
var errorK
Here is the full implementation with all the pieces put together:
First create an extension method:
public static class ModelStateHelper
{
public static IEnumerable Errors(this ModelStateDictionary modelState)
{
if (!modelState.IsValid)
{
return modelState.ToDictionary(kvp => kvp.Key,
kvp => kvp.Value.Errors
.Select(e => e.ErrorMessage).ToArray())
.Where(m => m.Value.Any());
}
return null;
}
}
Then call that extension method and return the errors from the controller action (if any) as json:
if (!ModelState.IsValid)
{
return Json(new { Errors = ModelState.Errors() }, JsonRequestBehavior.AllowGet);
}
And then finally, show those errors on the clientside (in jquery.validation style, but can be easily changed to any other style)
function DisplayErrors(errors) {
for (var i = 0; i < errors.length; i++) {
$("")
.html(errors[i].Value[0]).appendTo($("input#" + errors[i].Key).parent());
}
}