Skip to content

Instantly share code, notes, and snippets.

Created November 15, 2013 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/7483652 to your computer and use it in GitHub Desktop.
Save anonymous/7483652 to your computer and use it in GitHub Desktop.
Colections not null model binder
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Web.Mvc;
namespace Core.Web.Mvc.ModelProviders
{
/// <summary>
/// http://lostechies.com/jimmybogard/2013/11/07/null-collectionsarrays-from-mvc-model-binding/
/// Fixed
/// </summary>
public class CollectionsNotNullModelBinder : DefaultModelBinder
{
protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
{
if (value == null)
{
if (propertyDescriptor.PropertyType.IsArray)
{
value = Array.CreateInstance(propertyDescriptor.PropertyType.GetElementType(), 0);
}
else if (propertyDescriptor.PropertyType.IsGenericType)
{
Type typeToCreate = null;
Type genericTypeDefinition = propertyDescriptor.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(IDictionary<,>))
{
typeToCreate = typeof(Dictionary<,>).MakeGenericType(propertyDescriptor.PropertyType.GetGenericArguments());
}
else if (genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>) ||
genericTypeDefinition == typeof(IList<>))
{
typeToCreate = typeof(List<>).MakeGenericType(propertyDescriptor.PropertyType.GetGenericArguments());
}
if (typeToCreate != null)
{
value = Activator.CreateInstance(typeToCreate);
}
}
}
base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment