Created
November 8, 2013 09:33
-
-
Save feanz/7368603 to your computer and use it in GitHub Desktop.
BetterDefaultModelBinder means all collection properties are instantiated as empty collections not null.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ModelBinders.Binders.DefaultBinder = new BetterDefaultModelBinder(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment