Jeff Reddy
Jeff Reddy

Reputation: 5670

When to use IModelBinder versus DefaultModelBinder

I've got an MVC3 site that will has a model that won't work with default model binding. I've been looking at code samples on line, and it appears I could create a custom model binder that either implements IModelBinder or inherits from DefaultModelBinder. Can someone explain the pros/cons of each approach, and possibly example of when one approach would be used rather than the other.

Thanks in advance.

Upvotes: 15

Views: 2837

Answers (1)

Falanwe
Falanwe

Reputation: 4744

The two approaches are in fact the same one: DefaultModelbinder implements IModelBinder, so inheriting from it is a way as good as another to implement IModelBinder.

Pro for inheriting from DefaultModelBinder: you can reuse a lot of the behaviors from DefaultModelBinder, and override only the ones you want. You don't have to implement from scratch.

Pro for making your own implementation of IModelBinder: you only have one method to implement (IModelBinder.BindModel) and you have full control over what your implementation is doing.

The correct way largely depends on what you need from your custom binder, but the behavior of the DefaultModelBinder is usually what you need (and in most cases, plain old DefaultModelBinder is indeed the binder you want).

Upvotes: 12

Related Questions