Displaying model state errors after ajax call on Razor views

ajax, asp.net-mvc-3, validation

Solution

You can return errors with `Json` result (How to get all Errors from asp.net mvc modelState?):

var allErrors = ModelState.Values.SelectMany(v => v.Errors);

Then manually show errors. Get form validator:

var validator = $("form").validate();

Then check that your fields are initialized correctly, for example you can look here (optional step):

validator.settings.rules

OR

validator.settings.messages

If everything is fine, then you could show error:

validator.showErrors({"Password": "Too simple!"});

Where `Password` is field name and `Too simple!` is error message.

Problem

I have razor view with @Html.ValidationMessageFor helpers and jquery unobtrusive validation setup. I want to call controller/action and to show eventual model state errors returned by action by using same validation logic that is already set in place. I've made some code that does it but I was wondering if there is already way to do it automatically, i.e. if I capture HTTP Bad Request as AJAX response, I want to take out model state errors from response body and plug them in to unobtrusive validation. I'm looking for complete recommended solution, not workarounds :) Thanks!

Original source

Related problems