문제

It would be handy to limit the scope of a custom model binder for just a specific controller action method or its entire controller. Hanselman wrote a sentence that implied alternative locations for custom model binder registration but never seemed to finish the thought:

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

Is it possible to make these registrations at a smaller scope of the controller system? If so, is there any reason to avoid doing so outside of the Global.asax MvcApplication (e.g., performance reasons)?

도움이 되었습니까?

해결책

As I was closing the tabs I opened for this question that I hadn't reached before giving up, I found someone with an answer. You can assign a ModelBinderAttribute to your view models:

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

While it wasn't quite what I was looking for, it is even more specific than registering it for a controller or controller method.

Update

Thanks to Levi's comment pointing out a much better solution. If you are consuming the object with a custom model binder in an MVC action method directly, you can simply decorate that method's parameter with the ModelBinder property.

public ActionResult SomeMethod([ModelBinder(typeof(SomeEditorModelBinder))]SomeEditorModel model) { ... }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top