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 (6) -

  • James

    7/20/2018 10:12:01 PM | Reply

    Nice post.

  • dingdongstapling

    1/27/2019 7:39:37 AM | Reply

    Welcome to Shell Shockers! In this game you will become a soldier in the shape of an egg. Shoot ceaselessly, jump from one side to another, try to get through all obstacles and attack your opponents. How long do you think you can survive?
    http://shell-shockers.io/

  • Nurse offer

    4/21/2019 6:28:27 PM | Reply

    I dugg some of you post as I thought  they were  very helpful   handy

  • Hotel offer

    4/27/2019 11:27:41 PM | Reply

    I see  something really  interesting about your  website  so I  saved to bookmarks .

  • nasarawa nelajobs

    7/16/2019 7:17:08 PM | Reply

    As soon as I  detected  this  internet site  I went on reddit to share some of the love with them.

Loading