简体   繁体   English

定制模型绑定器

[英]custom modelbinder

I want to create a custom modelbinder which validates the bounded model. 我想创建一个自定义modelbinder来验证有界模型。 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. 我要实现的是控制器始终获取有效命令,因此无需在action方法中检查model.IsValid()。

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. 您可以使用其他属性,例如[OnError(“ Action”)],但这看起来像变通办法。
  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). 您可以设置全局操作过滤器(在基本控制器上),该过滤器将检查模型错误(绑定程序设置)并重定向(设置.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. 您仍然可以使用尽可能多的基础结构-模型绑定程序以提供ModelState错误等-但只有控制器才应对输入和输出拥有最终决定权。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM