eZeeNow.com

it's your's

MVC How to convert ModelState errors to json

How do you get a list of all ModelState error messages?

Method 1:


var errorList = (from item in ModelState
where item.Value.Errors.Any()
select item.Value.Errors[0].ErrorMessage).ToList();

var errorList = ModelState.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
);
Method 2: Using Helper class
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.Count() > 0);
}
return null;
}
}
Then call that extension method and return the errors from the controller action
if (!ModelState.IsValid)
{
return Json(new { Errors = ModelState.Errors() }, JsonRequestBehavior.AllowGet);
}
Render it in view
function DisplayErrors(errors) {
for (var i = 0; i < errors.length; i++) {
$("<label for='" + errors[i].Key + "' class='error'></label>")
.html(errors[i].Value[0]).appendTo($("input#" + errors[i].Key).parent());
}
}

Method 3: Using FOREACH help of StringBuilder

var stringBuilder = new StringBuilder()
sb.Append("[");
foreach (var pair in ModelState)
{
if (pair.Value.Errors.Count > 0)
{
sb.Append("{\""+pair.Key+"\":\""+ pair.Value.Errors.Select(error => error.ErrorMessage).SingleOrDefault()+"\"}|");
}
}
sb.Append("]");





Comments (1) -

Loading