How do I accept an array as an ASP.NET MVC controller action parameter?

The default model binder expects this url:

http://localhost:54119/Designs/Multiple?ids=24041&ids=24117

in order to successfully bind to:

public ActionResult Multiple(int[] ids)
{
    ...
}

And if you want this to work with comma separated values you could write a custom model binder:

public class IntArrayModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (value == null || string.IsNullOrEmpty(value.AttemptedValue))
        {
            return null;
        }

        return value
            .AttemptedValue
            .Split(',')
            .Select(int.Parse)
            .ToArray();
    }
}

and then you could apply this model binder to a particular action argument:

public ActionResult Multiple([ModelBinder(typeof(IntArrayModelBinder))] int[] ids)
{
    ...
}

or apply it globally to all integer array parameters in your Application_Start in Global.asax:

ModelBinders.Binders.Add(typeof(int[]), new IntArrayModelBinder());

and now your controller action might look like this:

public ActionResult Multiple(int[] ids)
{
    ...
}

Leave a Comment