ASP.NET MVC How to convert ModelState errors to json

前端 未结 13 2104
余生分开走
余生分开走 2020-12-04 05:24

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         


        
13条回答
  •  情歌与酒
    2020-12-04 05:41

    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());
        }
    }
    

提交回复
热议问题