Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 523
Jeff Reddy Avatar asked Dec 16 '11 14:12

Jeff Reddy


People also ask

What is the purpose of implementing the BindModel () method on the IModelBinder interface?

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.

What is a correct use case for creating a custom model binder in asp net core?

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.

Which option is a valid scenario for a custom model binder?

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.

Which interface should be implemented to create custom binder?

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.


1 Answers

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

like image 96
Falanwe Avatar answered Sep 18 '22 08:09

Falanwe