Skip to content

Instantly share code, notes, and snippets.

@jbogard
Created November 7, 2013 14:15

Revisions

  1. jbogard created this gist Nov 7, 2013.
    47 changes: 47 additions & 0 deletions BetterDefaultModelBinder.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    public class BetterDefaultModelBinder : DefaultModelBinder
    {
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
    var model = base.CreateModel(controllerContext, bindingContext, modelType);

    if (model == null || model is IEnumerable)
    return model;

    foreach (var property in modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
    {
    object value = property.GetValue(model);
    if (value != null)
    continue;

    if (property.PropertyType.IsArray)
    {
    value = Array.CreateInstance(property.PropertyType.GetElementType(), 0);
    property.SetValue(model, value);
    }
    else if (property.PropertyType.IsGenericType)
    {
    Type typeToCreate;
    Type genericTypeDefinition = property.PropertyType.GetGenericTypeDefinition();
    if (genericTypeDefinition == typeof(IDictionary<,>))
    {
    typeToCreate = typeof(Dictionary<,>).MakeGenericType(property.PropertyType.GetGenericArguments());
    }
    else if (genericTypeDefinition == typeof (IEnumerable<>) ||
    genericTypeDefinition == typeof (ICollection<>) ||
    genericTypeDefinition == typeof (IList<>))
    {
    typeToCreate = typeof(List<>).MakeGenericType(property.PropertyType.GetGenericArguments());
    }
    else
    {
    continue;
    }

    value = Activator.CreateInstance(typeToCreate);
    property.SetValue(model, value);
    }
    }

    return model;
    }
    }