asp.net-mvc-2 - 我可以在 Global.asax 以外的地方注册自定义模型绑定(bind)器吗?

标签 asp.net-mvc-2 custom-model-binder

将自定义模型绑定(bind)器的范围限制为仅用于特定 Controller 操作方法或其整个 Controller 会很方便。 Hanselman写了一个句子,暗示自定义模型绑定(bind)器注册的替代位置,但似乎从未完成这个想法:

You can either put this Custom Model Binder in charge of all your DateTimes by registering it in the Global.asax



是否可以在 Controller 系统的较小范围内进行这些注册?如果是这样,是否有任何理由避免在 Global.asax MvcApplication 之外这样做(例如,性能原因)?

最佳答案

当我关闭我为这个问题打开的选项卡时,我在放弃之前没有达到,我发现 someone with an answer .您可以分配 ModelBinderAttribute到您的 View 模型:

[ModelBinder(typeof(SomeEditorModelModelBinder))]
public class SomeEditorModel {
    // display model goes here
}
public class SomeEditorModelModelBinder : DefaultModelBinder {
    // custom model binder for said model goes here
}
虽然它不是我想要的,但它比为 Controller 或 Controller 方法注册它更具体。
更新
感谢 Levi 的评论指出了一个更好的解决方案。如果您直接在 MVC 操作方法中使用自定义模型绑定(bind)器来使用对象,您可以简单地使用 ModelBinder 装饰该方法的参数。属性(property)。
public ActionResult SomeMethod([ModelBinder(typeof(SomeEditorModelBinder))]SomeEditorModel model) { ... }

关于asp.net-mvc-2 - 我可以在 Global.asax 以外的地方注册自定义模型绑定(bind)器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3041242/

相关文章:

C# UTC 到用户本地时间

asp.net-mvc - 如何在 WebForms .aspx 页面中使用 ASP.Net MVC View ?

asp.net-mvc-2 - MVC 参数中的加号 (+) 在 IIS 7.0 上导致 404

asp.net-core - .NET Core 2 中缺少 TaskCache 类

asp.net-mvc - ASP.NET MVC - ID 字段的自定义模型绑定(bind)器

c# - 基于另一个列表过滤列表 - LINQ

asp.net-mvc-2 - 如何覆盖 ActionLink 行为

c# - 如何在 ASP.net 核心中为自定义模型绑定(bind)器编写单元测试

asp.net-mvc - 不区分大小写的模型绑定(bind) MVC 4