Displaying model state errors after ajax call on R

2020-05-20 08:54发布

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!

1条回答
叛逆
2楼-- · 2020-05-20 09:12

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.

查看更多
登录 后发表回答