bobby
bobby

Reputation: 637

Pass array of integers to Get / ASP.NET Web API

I know how to pass arrays to Get function like this: /?index=1&index=5&index=3

But I need to be able to receive arrays like this: /?index=[1,5,3]

Or something similarly short. Is there anything I can use?

Upvotes: 3

Views: 2226

Answers (1)

haim770
haim770

Reputation: 49095

Use a custom ModelBinder:

public class JsArrayStyleModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (value == null)
            return null;

        return new JavaScriptSerializer().Deserialize<string[]>(value.AttemptedValue);
    }
}

Then register it in your Global.asax:

ModelBinders.Binders.Add(typeof(string[]), new JsArrayStyleModelBinder());

Or directly on your Action parameter:

[HttpGet]
public ActionResult Show([ModelBinder(typeof(JsArrayStyleModelBinder))] string[] indexes)

Upvotes: 2

Related Questions