Created
November 15, 2013 12:33
-
-
Save anonymous/7483652 to your computer and use it in GitHub Desktop.
Colections not null model binder
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
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