在模型验证的 mvc 问题中返回 JavaScriptResult
我有 JavaScriptResult 的 post 方法的返回类型。我想通过 return new JavaScriptResult(){}
对此方法进行模型验证。我该怎么做?就像如果存在模型级别错误我应该返回什么一样。
I have a return type for a post method of JavaScriptResult. I want to do model validation for this method with return new JavaScriptResult(){}
. How can I do this? Like what should I return if a model level error exist.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,我会尽量避免使用 JavaScriptResult,因为它往往会将 UI 内容与控制器内容混合在一起,这往往违背整个 MVC 模式。如果我正在做您想要完成的事情,我会将
JsonResult
返回给客户端,然后根据结果执行一段代码。这样,如果模型验证失败,您可以返回包含失败结果的JsonResult
并在客户端上知道验证失败。它可以这样实现:}
然后客户端代码:
但是,如果您需要使用
JavaScriptResult
路由并且发生验证错误,我将不返回任何内容,或者返回一些 javascript 来通知用户验证失败:Generally, I would try to avoid using
JavaScriptResult
as it tends to intermingle UI content with controller content, which tends to go against the whole MVC pattern. If I were doing what you were trying to accomplish I would return aJsonResult
back to the client and then execute a block of code based on the result. This way if a model fails validation you could return aJsonResult
with a failure result and know on the client that the validation failed. It can be achieved like this:}
Then client code:
However, if you need to go the
JavaScriptResult
route and a validation error occurs, I would either return nothing or some javascript that would notify the user that the validation failed: