5

I'm using Web API (part of ASP.NET MVC 5), and I'm trying to bind querystring values to a Dictionary<int, bool>.

My Web API method is simply:

[HttpGet]
[Route("api/items")]
public IQueryable<Item> GetItems(Dictionary<int, bool> cf)
{
    // ...
}

If I try to invoke this URL:

/api/items?cf[1009]=true&cf[1011]=true&cf[1012]=false&cf[1015]=true

The parameter cf is always null.

How can I pass in a dictionary of values via the QueryString to a Web API method?

qJake
  • 16,821
  • 17
  • 83
  • 135

3 Answers3

8

When you want to pass a dictionary (basically key and value pair) using a query string parameter then you should use format like: &parameters[0].key=keyName&parameters[0].value=keyValue

In my Action method signature, parameters is defined as:

Dictionary<string,string> parameters

Hope this helps.

I was able to figure this our myself after reading this post from Scott Hanselman. So thanks to Scott!!

Thanks, Nirav

Mikhail Antonov
  • 1,297
  • 3
  • 21
  • 29
Nirav Darji
  • 128
  • 1
  • 6
  • This is the correct answer, but I was not in control of the URL so this didn't work for me (I couldn't append `.key`/`.value`) - I ended up just manually iterating through `Request.Form` and parsing the results by hand. – qJake Jun 10 '20 at 14:24
0

There is no built-in way of doing this. On this case, "cf[1009]" is the name of the parameter, not "cf". You can write you own query string parser to achieve what you need. A better signature would be:

/api/items?cf=1009&cf=1011&cf=1015

And you bind it by using:

public IQueryable<Item> GetItems(List<int> cf)
{
    // ...
}
Marcelo Calbucci
  • 5,845
  • 3
  • 18
  • 22
0

You can create a ModelBinder for your dictionary, as described on this post:

https://stackoverflow.com/a/22708383

Community
  • 1
  • 1
  • 2
    While this link may answer the question, [it is better](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Keale Jul 01 '16 at 02:00