ASP.NET MVC How to convert ModelState errors to json

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

    @JK it helped me a lot but why not:

     public class ErrorDetail {
    
            public string fieldName = "";
            public string[] messageList = null;
     }
    

            if (!modelState.IsValid)
            {
                var errorListAux = (from m in modelState 
                         where m.Value.Errors.Count() > 0 
                         select
                            new ErrorDetail
                            { 
                                    fieldName = m.Key, 
                                    errorList = (from msg in m.Value.Errors 
                                                 select msg.ErrorMessage).ToArray() 
                            })
                         .AsEnumerable()
                         .ToDictionary(v => v.fieldName, v => v);
                return errorListAux;
            }
    

提交回复
热议问题