ASP.NET MVC How to convert ModelState errors to json

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

    Why not return the original ModelState object to the client, and then use jQuery to read the values. To me it looks much simpler, and uses the common data structure (.net's ModelState)

    to return the ModelState as Json, simply pass it to Json class constructor (works with ANY object)

    C#:

    return Json(ModelState);
    

    js:

            var message = "";
            if (e.response.length > 0) {
                $.each(e.response, function(i, fieldItem) {
                    $.each(fieldItem.Value.Errors, function(j, errItem) {
                        message += errItem.ErrorMessage;
                    });
                    message += "\n";
                });
                alert(message);
            }
    

提交回复
热议问题