Search code examples
asp.net-mvcdesign-patternsmodel-view-controllermvvmcustom-model-binder

Should I use custom model binder to bind view model to entity?


Just some idea to make more use of custom model binder. I am currently still using IMapper interface to do so, though wondering whether part of the purpose of custom binder is to mapping view model or input model to business entity? I can see there might be some limitations if i use MVC custom binder. What is the advantage to use the custom binder in MVC? Will my app gain better performance?


Solution

  • Short answer would be No, you should not

    ModelBinder by itself is part of ASP.NET MVC infrastructure. If you would take a look at ASP.NET MVC pipline (PDF) you would see that it's job is to convert a posted web form data (a string basically) or query string from URL to an instance of particular class.
    ASP.NET MVC framework has a DefaultModelBinder that is suitable for 99% of cases. Custom model binders could be used in situations where standard data conversion fails e.g. mapping $ 1,234.56 from a textbox to a decimal value of 1234.56

    Moreover ModelBinder implements IModelBinder interface with a single BindModel() method. This method expects parameters that would be hard to 'hand-craft' to make any use of them and are totally not relevant to your scenario.

    What you are realy looking for is
    - either custom object mapping between viewmodels and business objects where you manually assign one object property values to another
    - or taking advantage of libs/frameworks such as Automapper or ValueInjecter which take care of object mapping hassle away from you
    - or a mix of both