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.
MVC uses following types for Model Binding: IModelBinder interface - This defines methods that are required for a Model Binder, like the BindModel method. This method is responsible for binding a model to some values using ControllerContext and BindingContext.
You might need to transform the input prior to binding it. For example, when you have a key that can be used to look up model data. You can use a custom model binder to fetch data based on the key.
We can apply custom model binder using ModelBinder attribute by defining attributes on action method or model. If we are using this method (applying attribute on action method), we need to define this attribute on every action methods those want use this custom binding.
For creating a custom model binder class, we have to inherit from IModelBinder interface. This interface has an async method named "BindModelAsync" and it has a parameter of type ModelBindingContext. The ModelBindingContext class provides the context that model on which the binder acts.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With