15

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.

Jeff Reddy
  • 5,551
  • 9
  • 55
  • 88
  • You've likely already seen it, but there are several good references here: http://stackoverflow.com/questions/1550520/best-practices-when-implementing-imodelbinder – Shawn Dec 16 '11 at 14:52

1 Answers1

12

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).

Falanwe
  • 4,636
  • 22
  • 37
  • So, based on what you have said, if I have 3 properties that the MVC default binding doesn't work with, I should inherit from DefaultModelBinder, allow it to bind the majority of my model, and then handle the binding of my 3 unique properties? – Jeff Reddy Dec 16 '11 at 16:02
  • 1
    That's the idea. I can't be more precise without more precisions about your model though. The DefaultModelBindel does a lot of things, so it would be a shame not to take advantage of it. – Falanwe Dec 16 '11 at 17:20
  • I'm binding an property of type Dictionary. While the default works, it doesn't work the way I need it to. I'm using custom helpers to build the view from these properties and the binding needs to work with what I've done on that side. – Jeff Reddy Dec 16 '11 at 18:06
  • 1
    Indeed, if you use custom helpers to create your view, you cannot rely on the DefaultModelBinder to understand the result (the binding sometimes feels magical, but not this magical!). Take advantage of the DefaultModelBinder for most of your model and modify its behavior regarding dictionaries. – Falanwe Dec 17 '11 at 07:29