May 06

The S#arp framework: the SharpModelBinder

Posted in S#arp      Comments Off on The S#arp framework: the SharpModelBinder

In the last post, we’ve looked at several classes that improve the default binding you get in ASP.NET MVC. Today, we’re going to end the Sharparch.Web assembly study and we’ll take a deep look at the SharpModelBinder custom binder. This custom binder performs the following actions on the OnModelUpdated override:

  • starts by removing all errors that aren’t parsing related;
  • then it copies all validation errors exposed by the validated object to the current model state dictionary.

This behavior is slightly different than the one we had with the ValidatableModelBinder we’ve met in a previous post. Besides doing this stuff in the OnModelUpdated override, this custom binder will also retrieve associated one-to-one and one-to-many properties which are associated with other entities. This work is performed on the override of the BindProperty method.

This method starts by checking if the property’s type implements the IEntityTypedId<> interface. When that happens, it will replace the default ValueProviderResult of that type for the custom EntityValueProviderResult and this new custom provider will be used for populating the property with the correct reference.

The EntityValueProviderResult does most of  its work by overriding the ConvertTo method. As you might expect (especially if you’ve been following along), it uses the service locator pattern for getting a reference to the correct repository that is responsible for loading entities of that type.

If you want to use this type, then you can make it the default binder or associate it with a specific type. Making it the default binder is really easy (and probably recommended if you’re using this framework):

ModelBinders.Binders.DefaultBinder = new SharpModelBinder();

And then, you can proceed almost as if you’re using the standard binder. Here’s an example:

public ActionResult DoSomething(SomeObjectWithRelationsToOtherEntities myObject) {
  if (ViewData.ModelState.IsValid ) {
          return RedirectToAction("Index");

   return View(myObject);

I’m still no sure if I’ll ever use this approach.  I guess that it’s perfect for scenarios where you’re using ORM and are concentrating on relationships, but I’m still unsure of its use in complex domain scenarios – but again, I’m starting to convince myself that probably ORMs and databases aren’t the best place to keep track of my writing transactions!,,)

And that’s it…more to come about this framework in the future. Keep tuned.