自定义模型绑定器

发布于 2024-09-07 07:07:51 字数 174 浏览 5 评论 0原文

我想创建一个自定义模型绑定器来验证有界模型。我找到了几个这样的例子,它的工作原理应该是这样的。但如果模型中存在错误,我还希望能够将用户发送回他来自的页面。

这可以做到吗?这样做有任何明显的副作用吗?

我想要实现的是控制器始终获取有效命令,因此我不需要在操作方法中检查 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼泪也成诗 2024-09-14 07:07:51

你尝试做的事情看起来不错,但行不通。限制太多了。

  1. 通常,只有控制器可以决定在发生错误时重定向到哪里。您可以使用 [OnError("Action")] 等其他属性,但这看起来像是解决方法。
  2. 表单不会发布所有数据。例如,下拉列表、辅助值必须由控制器填充。您可能可以使用操作过滤器来实现此目的,但这再次看起来像是一个黑客行为。

您可以设置全局操作过滤器(在基本控制器上),该过滤器将检查模型错误(绑定器设置)并重定向(设置.Result)。但这很复杂,并且需要太多额外的“代码”——属性等,从而很难跟踪并与真实的应用程序逻辑关联。当您不仅仅需要错误重定向上的简单操作名称等时,它很快就会变得过于严格(参见泄漏抽象法则)。

这样做看起来要简单得多

public ActionResult PostAction(ViewModel data)
{
   if (!ModelState.IsValid)
      return View("GetAction", data.WithDropDownList(repository.GetProducts()));

}

在上面的示例中,控制器可以控制工作流程,正如它应该的那样。它还可以自由地执行额外的验证/设置。您仍然可以使用尽可能多的基础设施 - 模型绑定器来提供 ModelState 错误等 - 但只有控制器应该对输入和输出做出最终决定。

What you try to do looks good, but it won't work. There're too many restrictions.

  1. Usually, only controller can decide where to redirect in case of an error. You can use additional attributes like [OnError("Action")] but this looks like workarounds.
  2. Form doesn't post all data. For example, dropdown lists, auxiliary values have to be filled by controller. You can probably use action filters for this but this is once again looks like a hack.

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:

public ActionResult PostAction(ViewModel data)
{
   if (!ModelState.IsValid)
      return View("GetAction", data.WithDropDownList(repository.GetProducts()));

}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文