自定义模型绑定器
我想创建一个自定义模型绑定器来验证有界模型。我找到了几个这样的例子,它的工作原理应该是这样的。但如果模型中存在错误,我还希望能够将用户发送回他来自的页面。
这可以做到吗?这样做有任何明显的副作用吗?
我想要实现的是控制器始终获取有效命令,因此我不需要在操作方法中检查 model.IsValid() 。
I want to create a custom modelbinder which validates the bounded model. I have found several examples of this and it works as it should. But I want to also to be able to send the user back to the page he came from if there is errors in the model.
Is this possible to do and are there any obvious side effects by doing this?
What I want to achieve is that the controller always gets valid commands, so I do not need to check for model.IsValid() in the action method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你尝试做的事情看起来不错,但行不通。限制太多了。
您可以设置全局操作过滤器(在基本控制器上),该过滤器将检查模型错误(绑定器设置)并重定向(设置.Result)。但这很复杂,并且需要太多额外的“代码”——属性等,从而很难跟踪并与真实的应用程序逻辑关联。当您不仅仅需要错误重定向上的简单操作名称等时,它很快就会变得过于严格(参见泄漏抽象法则)。
这样做看起来要简单得多:
在上面的示例中,控制器可以控制工作流程,正如它应该的那样。它还可以自由地执行额外的验证/设置。您仍然可以使用尽可能多的基础设施 - 模型绑定器来提供 ModelState 错误等 - 但只有控制器应该对输入和输出做出最终决定。
What you try to do looks good, but it won't work. There're too many restrictions.
You can setup global action filter (on base controller) that will check for model errors (that binder sets) and redirect (setup .Result). But this is convoluted and requires too much extra "code" - attributes, etc., that is then hard to track and relate to real application logic. And it becomes too restrictive soon (see law of leaky abstraction), when you need not just simple action name on error redirect, etc.
This looks much simpler when done like this:
In the above example, controller has the control over the workflow, just as it should be. It also has freedom to perform additional verification/setup. You can still use as much infrastructure as possible - model binders to provide ModelState errors, etc - but only controller should have the final decision on the input and output.