IModelBinder with AutoBinder

Today I noticed this post on the ModelBinder attribute that ships with Preview 5 of ASP.NET MVC. I looked at the example and it doesn't make any sense.  I had come up with something I call AutoBinder and until today didn't think it was anything worth mentioning.  I could swear I saw somewhere that something like this would be included in the RTM of MVC but I can't remember where I saw that.

IModelBinder

IModelBinder is a simple interface with one method to implement, it looks like this:


public interface IModelBinder {
  object GetValue(ControllerContext controllerContext, string modelName, Type modelType, ModelStateDictionary modelState);
}
1
2
3

AutoBinder

AutoBinder simply implements that interface like this:


public class AutoBinder : IModelBinder where TModel : class, new(){
  public object GetValue(ControllerContext controllerContext, string modelName,
    Type modelType, ModelStateDictionary modelState){
    return AutoBinder.UpdateFrom(controllerContext);
  }
}
1
2
3
4
5
6

And AutoBinder.UpdateFrom looks like this:


public static T UpdateFrom(ControllerContext controllerContext) where T : class, new(){
  T result = new T();
  NameValueCollection form = controllerContext.HttpContext.Request.Form;
  foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(result)){
    object value = null;
    //if the property type is boolean, make sure it's not an array, the
    //default behavior of Html.CheckBox is to create the checkbox, plus
    //a hidden field with the same name as the checkbox, to cover the behavior
    //of when a checkbox is unchecked, it won't get posted
    if (property.PropertyType == typeof(bool)){
      string[] values = form[property.Name].Split(',');
      if (values.Length > 0){
    	value = ConvertUtils.ChangeType(values[0], property.PropertyType);
      }
    }else{
      value = ConvertUtils.ChangeType(form[property.Name], property.PropertyType);
    }
    property.SetValue(result, value);
  }
  return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

Using AutoBinder

Using this requires either registering the types with their appropriate binder at app startup or adorning your models with the ModelBuilder attribute like so:


[ModelBinder(typeof(AutoBinder))]
public class Customer{
//guts of Customer here
}
1
2
3
4

Now in a controller we might have a method that looks like this:


[AcceptVerbs("POST")]
public ActionResult Edit(Customer customer){
//blah blah blah
}

1
2
3
4

Assuming that all of the fields on the form have the same name attribute as the properties on the model, the customer arg will be mapped up with the posted form values automagically through the ModelBinder attribute.

Anyway, here's the spectacular example: ModelBinder.zip.  It assumes that you have Preview 5 of ASP.NET MVC installed.

 
Author: , 0000-00-00