Thursday, 28 April 2016

MVC.NET ModelBinder to accept traditional and non-traditional style arrays (with square brackets)

MVC controller expects arrays in request like http://localhost?data=1&data=2&data=3
But how to get it work with PHP-style arrays like http://localhost?data[]=1&data[]=2&data[]=3
The ModelBinder below accepts both styles at the same time.

Class:
        public class PhpStyleArrayBinder : DefaultModelBinder,IModelBinder
        {
            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
            {
                var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName+"[]");
                if (val != null)
                    return val;
                return base.BindModel(controllerContext, bindingContext);
            }
        }
Usage:

        public JsonResult Get([ModelBinder(typeof (PhpStyleArrayBinder))] IEnumerable<string> data)
        {
            //
        }