Julian Jelfs’ Blog

“Patch” model binding with Asp.Net MVC

Posted in MVC by julianjelfs on March 8, 2013

Let’s say you have an update Action on a controller in Asp.Net MVC that accepts a domain object which you use for updating something like this:

[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ViewResult UpdateCustomer(Customer model)
{
    //persist your model somehow etc etc
    return View(model);
}

When you use the DefaultModelBinding the MVC framework will create an instance of the Customer class and fill in any properties that it finds according to the registered ValueProviders (which will pull parameters from various places like the Form and the QueryString etc). This is all very well described here.

But what happens if you have more than one view of the data and sometimes not all of the data is passed back with the form? When might this happen? Perhaps you have a workflow where one user enters some of the data and another user completes the data. You could achieve this with two models and two views and two controller actions but you might have a dynamic view and just pass back the data that user is required to fill in (or has access to).

In this scenario, the DefaultModelBinder will cause us a problem because it creates a new instance of the Customer class to bind to. So suppose that user A has filled out the customer’s name and saved, but user B has to fill out the customer’s address but does not have access to the customer’s name (not very realistic I know). In this case the form posted by user B will not contain a value for the customer’s name, so that value will not be bound and user A’s data will get overwritten with a null value when the model is persisted.

You might be able to handle this with validation, but there is no point giving user B a validation error message relating to a field that he cannot see.

One way to deal with this is to create a custom model binder that loads the existing state of the model before binding rather than loading a blank instance of the type. It might look something like this:

public class CustomerModelBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext, 
                                    ModelBindingContext bindingContext, Type modelType)
    {
        var session = ServiceLocator.Current.GetInstance<IDocumentSession>();
        var val = bindingContext.ValueProvider.GetValue("model.Id");    //this could be parameterised
        if (val != null)
        {
            var customer = session.Load<Customer>(val.AttemptedValue);
            if (customer != null)
            {
                return customer;
            }
        }
        return base.CreateModel(controllerContext, bindingContext, modelType);
    }
}

In this code, we are checking to see if the ValueProvider has a value for the key to our model object. If it does, we load the object (I’m using Raven but that doesn’t matter), if not we fallback to the DefaultModelBinder.

We then need to register this custom model binder for the specific type we are interested in at application start up;

ModelBinders.Binders.Add(typeof(Customer), new CustomerModelBinder());
And now, when user B’s partially complete POST arrives, it will be bound to the instance of the Customer object that user A created and we will not lose any data. Nice.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: