Created
May 7, 2015 17:52
-
-
Save programcsharp/71fadf02645f23f5d6d0 to your computer and use it in GitHub Desktop.
CommaSeparatedModelBinder array fix
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
private object BindCsv(Type type, string name, ModelBindingContext bindingContext) | |
{ | |
if (type.GetInterface(typeof(IEnumerable).Name) != null) | |
{ | |
var actualValue = bindingContext.ValueProvider.GetValue(name); | |
if (actualValue != null) | |
{ | |
var valueType = type.GetElementType() ?? type.GetGenericArguments().FirstOrDefault(); | |
if (valueType != null && valueType.GetInterface(typeof(IConvertible).Name) != null) | |
{ | |
var list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(valueType)); | |
Type rawType = actualValue.RawValue.GetType(); | |
if (rawType.IsArray && ((Array)actualValue.RawValue).Length > 1) | |
{ | |
foreach (object value in (IEnumerable)actualValue.RawValue) | |
list.Add(Convert.ChangeType(value, valueType)); | |
} | |
else | |
{ | |
foreach (var splitValue in actualValue.AttemptedValue.Split(new[] { ',' })) | |
{ | |
if (!String.IsNullOrWhiteSpace(splitValue)) | |
list.Add(Convert.ChangeType(splitValue, valueType)); | |
} | |
} | |
if (type.IsArray) | |
return ToArrayMethod.MakeGenericMethod(valueType).Invoke(this, new[] { list }); | |
else | |
return list; | |
} | |
} | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment