Skip to content

Instantly share code, notes, and snippets.

@roryf
Created March 29, 2012 16:09
Show Gist options
  • Save roryf/2239068 to your computer and use it in GitHub Desktop.
Save roryf/2239068 to your computer and use it in GitHub Desktop.
An ASP.NET MVC ModelBinder for binding form values of the form name[].property rather than name[index].property. Assumes form values are POSTed in markup order, unsure if this is always true.
public class IndexlessEnumerableModelBinder<TItemType> : DefaultModelBinder
where TItemType : class
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
{
if (typeof(IEnumerable<TItemType>).IsAssignableFrom(propertyDescriptor.PropertyType))
{
var nameOfPropertyToBind = propertyDescriptor.Name;
var form = controllerContext.HttpContext.Request.Form;
var result = new List<TItemType>();
foreach (var key in form.AllKeys)
{
var matches = Regex.Matches(key, string.Format(@"^{0}\[\]\.(\w+)", nameOfPropertyToBind));
if (matches.Count > 0)
{
var propertyName = matches[0].Groups[1].Value;
var propertyInfo = typeof (TItemType).GetProperty(propertyName);
if (propertyInfo == null)
{
continue;
}
var values = bindingContext.ValueProvider.GetValue(key).ConvertTo(propertyInfo.PropertyType.MakeArrayType()) as IEnumerable;
if (values == null)
{
continue;
}
var index = 0;
foreach (var value in values)
{
if (result.Count <= index)
{
result.Add(Activator.CreateInstance<TItemType>());
}
propertyInfo.SetValue(result[index], value, null);
index++;
}
}
}
SetProperty(controllerContext, bindingContext, propertyDescriptor, result);
return;
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
@larscmagnusson
Copy link

Great :)

@jrichview
Copy link

Might want to show how to apply this in an MVC app? Or at least reference a link maybe?

@larscmagnusson
Copy link

Might want to show how to apply this in an MVC app? Or at least reference a link maybe?

Classic .NET? Look at https://www.codeproject.com/Articles/605595/ASP-NET-MVC-Custom-Model-Binder

.NET Core?
https://docs.microsoft.com/en-us/aspnet/core/mvc/advanced/custom-model-binding?view=aspnetcore-5.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment