我和@ 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
错误的结果(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.