Skip to content

Instantly share code, notes, and snippets.

@programcsharp
Created May 7, 2015 17:52
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 programcsharp/71fadf02645f23f5d6d0 to your computer and use it in GitHub Desktop.
Save programcsharp/71fadf02645f23f5d6d0 to your computer and use it in GitHub Desktop.
CommaSeparatedModelBinder array fix
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