在剃刀意见AJAX调用后显示模式状态误差 [英] Displaying model state errors after ajax call on Razor views

查看:146
本文介绍了在剃刀意见AJAX调用后显示模式状态误差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我和@ Html.ValidationMessageFor助手和jQuery不显眼的验证设置剃刀视图。

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.

我做了一些code,做它,但我不知道是否已经有办法来自动执行,也就是说,如果我捕捉HTTP错误请求为Ajax响应,我要拿出从响应模型状态错误身体然后将它们插入到不引人注目的验证。

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 :)

谢谢!

推荐答案

您可以返回与的Json 错误的结果(<一href="http://stackoverflow.com/questions/1352948/how-to-get-all-errors-from-asp-net-mvc-modelstate">How让所有的错误,从asp.net MVC的ModelState ):

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

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.

这篇关于在剃刀意见AJAX调用后显示模式状态误差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆