开发者

Is it possible to set custom ModelBinder for the whole controller?

I've a custom model binder and I开发者_高级运维 know two ways of assigning this to my action method:

Either at the method:

public ActionResult MyAction([ModelBinder(typeof(MyCustomModelBinder))] ModelClass filter

Or globally in global.asax.cs:

ModelBinders.Binders.Add(typeof(MyCustomModelBinder))

But I wonder if there is a way to assign the custom model binder on the controller? So it works for all methods in the controller but not globally?


In your model binder you have access to the ControllerContext. So it should be easy to bind your model based on the controller information you have available there.

It does smell a bit because you are creating a coupling between your model binding and the controller. But if you use DI to create a strategy pattern and inject a binder resolver into a ModelBinderContainer which then uses its knowledge of your system to choose the desired binding you would have your solution.


No and as far as I know and it does not make much sense logically since a ModelBinder is bound to a Model either globally in the Binders collection (or by adding the attribute directly on the model class) or locally on a model in an action.

However you can still achieve what you want by creating an Aspect (as in from Aspect Oriented Programming) with a tool like PostSharp. You will be able to apply that aspect on the Controller level and it will inject the ModelBinder attributes on all methods as a post-compilation step. Question is whether you want to go through all this trouble and more importantly will it bring any value.

An example of an attribute decorator aspect is available in the PostSharp documentation here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜