Sunday, June 3, 2012

Thoughts on ModelBinders


Validation
Source: http://www.markeverard.com/blog/2011/07/18/creating-a-custom-modelbinder-allowing-validation-of-injected-composite-models/

Custom ModelBinders don’t seem to run validation on the newly created model automatically, so while you may add validation attributes to your model you need to add in some extra code to force validation to occur.

There may be a class you can override to get this automatically but I haven’t found it yet.

Entities 
Source: http://lostechies.com/jimmybogard/2011/07/07/intelligent-model-binding-with-model-binder-providers/

An interesting technique I’ve seen used is using modelbinding to automatically load an entity based on the id passed in. So your actions ask for an entity instead of an Id.

Doesn’t seem like much but it should remove 1 line from most actions (loading the entity from the database). However it requires you to never use your entities as edit models (which you shouldn’t be doing anyway). It also doesn’t allow extra filtering/including of data that I can tell.

This idea could be extended to work on list pages by creating a filter criteria from all route values (page, sort, search)

Dependency Injecting Model Binders
Source: http://iridescence.no/post/Constructor-Injection-for-ASPNET-MVC-Model-Binders.aspx

Out of the box you can’t use dependency injection with ModelBinders, you can however pass objects in when you create them at registration time.  If your ModelBinders only take singletons then that approach works, otherwise create a fairly basic modelbinder that takes your kernel as a parameter and when binding method is called use the kernel to create your real model binder complete with full dependency injection.

DateTimes
For a recent projet I didn’t want to use a javascript datetime picker as it was meant to be used on a horrible android tablet, but I still wanted something a bit friendlier than a textbox.  I chose to split dates into day/month/year fields, which would be a lot of effort to do to every date manually.

Instead I made an Editor Template for DateTimes which outputs 3 fields, and a custom ModelBinder that when binding dates looks for 3 fields instead of just 1.