ASP.NET MVC How to convert ModelState errors to json

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

      List Errors = new List(); 
    
    
            //test errors.
            var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);
    
            foreach (var x in modelStateErrors)
            {
                var errorInfo = new ErrorList()
                {
                    ErrorMessage = x.ErrorMessage
                };
                Errors.Add(errorInfo);
    
            }
    

    if you use jsonresult then return

    return Json(Errors);
    

    or you can simply return the modelStateErrors, I havent tried it. What I did is assign the Errors collection to my ViewModel and then loop it..In this case I can return my Errors via json. I have a class/model, I wanted to get the source/key but I'm still trying to figure it out.

        public class ErrorList
    {
        public string ErrorMessage;
    }
    

提交回复
热议问题