ASP.NET MVC How to convert ModelState errors to json

前端 未结 13 2085
余生分开走
余生分开走 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:49

    Variation with return type instead of returning IEnumerable

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

提交回复
热议问题