Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying model state errors after ajax call on Razor views

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!

like image 328
Admir Tuzović Avatar asked Oct 26 '12 19:10

Admir Tuzović


People also ask

What does ModelState IsValid validate?

ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process.


1 Answers

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.

like image 189
webdeveloper Avatar answered Sep 23 '22 08:09

webdeveloper