You can create custom model binders to abstract and centralise complex mapping logic that would otherwise end up in your controllers or services. When dealing with a larger number of binders, it is good to refactor common logic and enable wiring up of the new binders easily. Instead of having to register each binder one-by-one in global or prefix the type in the actions, we can create our own model binder broker to replace the default MVC DefaultModelBinder.

A Common Scenario

Retrieving a persisted domain object from the database that is then passed to the ViewModel. Lets assume we have a database of books and we want to get a single book by it’s ID.

Binder Code

Rather than doing all the lookup work in the controller, you can create a BookBinder that will call the repo and retrieve the Book object by given ID. The BinderBase expects the type of the domain object and the type of the ID. It auto-converts the value from IValueProviders into the expected ID type and calls BindModelWithId.

Using Model Binders To Retrieve The Book Object

A Smart Way To Wire-Up Your Model Binders

Registering binders one-by-one in the Global.asax or prefixing them in the Action gets tedious and it’s easy to make a mistake. A smarter way is to implement a default model binder and decide which binder to use based on ShouldBind property of each IFilteredBinder.