5

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

您可以通过在 Global.asax 中注册此自定义模型绑定器来负责您的所有日期时间

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

4

1 回答 1

6

当我关闭我为这个问题打开的选项卡时,我在放弃之前没有达到,我找到了一个有答案的人。您可以将 a 分配ModelBinderAttribute给您的视图模型:

[ModelBinder(typeof(SomeEditorModelModelBinder))]
public class SomeEditorModel {
    // display model goes here
}
public class SomeEditorModelModelBinder : DefaultModelBinder {
    // custom model binder for said model goes here
}

虽然这不是我想要的,但它比为控制器或控制器方法注册它更具体。

更新

感谢 Levi 的评论指出了一个更好的解决方案。如果您直接在 MVC 操作方法中使用自定义模型绑定器使用该对象,则可以简单地使用该属性装饰该方法的参数ModelBinder

public ActionResult SomeMethod([ModelBinder(typeof(SomeEditorModelBinder))]SomeEditorModel model) { ... }
于 2010-06-14T22:04:40.650 回答