简体   繁体   English

绕过 asp.net MVC 中的 model 绑定器以获得复杂的动作参数?

[英]Bypass model binders in asp.net MVC for complex action parameters?

Is there an attribute that can turn off model binding for complex action parameters?是否有一个属性可以关闭复杂动作参数的 model 绑定?

My scenario is this: I'm using Linq to SQL but make the generated classes implement interfaces.我的场景是这样的:我使用 Linq 到 SQL 但使生成的类实现接口。 For example, IUser.例如,IUser。 Some of my controllers actions accept IUser parameters and some of my views bind IUser models, but I don't want the default model binder to construct it.我的一些控制器操作接受 IUser 参数,而我的一些视图绑定 IUser 模型,但我不希望默认的 model 绑定器来构造它。 I use Action Filters for that.我为此使用动作过滤器。 The idea behind this is that if an action requires user details, the action filter gets it from the database before the action is invoked.这背后的想法是,如果某个操作需要用户详细信息,则操作过滤器会在调用该操作之前从数据库中获取它。

To get around the error that occurs when the DefaultModelBuilder gets fired up, I've made a null model binder that just returns null from CreateModel.为了解决 DefaultModelBuilder 启动时发生的错误,我制作了一个 null model 绑定器,它只从 CreateModel 返回 null。

ModelBinderDictionary binders = System.Web.Mvc.ModelBinders.Binders;
binders[typeof(IUser)] = new NullModelBinder();

Would it not be simpler to follow the architecture and create an IUser binder that does what your action filter is doing?遵循架构并创建一个 IUser 绑定器来执行您的操作过滤器正在执行的操作不是更简单吗? Currently you are perverting the action filter to do something it is not entirely intended to do and in the process you have also ignored the extension point designed specifically for doing what you are trying to achieve ( create an instance of a parameter in a specific manner ).目前,您正在扭曲动作过滤器来做一些它不完全打算做的事情,并且在这个过程中,您还忽略了专门为做您想要实现的事情而设计的扩展点(以特定方式创建参数的实例) .

Is there good reason you are creating the IUser in the action filter rather than with a custom binder?您是否有充分的理由在操作过滤器中创建 IUser 而不是使用自定义活页夹?

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

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