2010-07-11

TwoRingBinder - a Custom ASP.NET MVC Model Binder

I haven't posted in a few months. Been busy at work and starting playing WoW (I know -- its awful but its fun). But a few weeks ago I made a Custom ModelBinder -- called TwoRingBinder -- for ASP.NET MVC. Ok, it's not an implementation but rather a class inheriting from DataAnnotationsModelBinder that allows for easier custom Binding methods. I put it on github but will explain how to use it below.

Download

or check out the meat of the code.

Essentially, TwoRingBinder allows you to write Binding Extensions instead of writing your own Custom Model Binder every time you want to do something tricky or different with Model Binding.

Example: We have a model called SignUp. SignUp has FirstName, LastName, Origin, IsFemale and FromRoot properties. Only the FirstName and LastName properties will be bound from a form via a ValueProvider; however, we need IsFemale to have a value (assume for a service of some type). Now, we don't want a checkbox on the site for people to select if they are female -- we want to just guess it based on their name (an arbitrary example to say the least). With TwoRingBinder we can do this two ways (get it?!?!).

Ring One: we can implement a method (or two) on our model -- the method(s) must be named OnBound or OnBinding.

Ring Two: we can implement a IBindModelExtension -- which is a generic of our Model, SignUp. The extension can have one or two methods, PreBindModel and PostBindModel.

Let's set a value for IsFemale automatically using TwoRingBinder, see:



private readonly string[] _girlsNames = new[] { "Elaine", "Stephanie", "Jennifer" };

public void PostBindModel(SignUp boundModel, ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
boundModel.IsFemale = _girlsNames.Contains(boundModel.FirstName);
}


It's not that much code but I've found TwoRingBinder super useful for those types of situations where a Custom Model Binder isn't appropriate. Plus the IBindModelExtensions can be organized & clean -- separate from your Controllers and Models (which they are neither). Or if you so desire, the logic can be a part of the Model itself. I think where you place the OnBind / OnBound logic depends entirely upon what you are doing.

No comments: