jQuery Validate, ASP.NET MVC ModelState Errors (Async POST)

前端 未结 4 1541
遥遥无期
遥遥无期 2021-01-30 07:29

I\'m developing a web app with asp.net mvc 3 and I have some form that POST to an async action (via ajax). This action recives a ViewModel with some data annotations to validate

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-30 08:06

    You could return the ModelState errors. This is untested, but something like this should work.

    return Json(new
                {
                    success = false,
                    errors = ModelState.Keys.SelectMany(k => ModelState[k].Errors)
                                    .Select(m => m.ErrorMessage).ToArray()
                });
    

    Edit: To display the errors in a view you just check to see if you were successful, and if not, iterate over the list of errors and put them where you show your errors.

    if(!result.success) {
        for(var error in result.errors) {
            $('#errorMessages').append(error + '
    '); } }

    I prefer Darin's answer for most projects, but your consumer may not always be your own application in which case returning a list of errors is more appropriate since it would allow the consumer to display the errors however they want.

提交回复
热议问题