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
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.