Binding querystring values to a dictionary

风格不统一 提交于 2020-01-03 12:34:49

问题


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?


回答1:


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




回答2:


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)
{
    // ...
}



回答3:


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

https://stackoverflow.com/a/22708383



来源:https://stackoverflow.com/questions/29320452/binding-querystring-values-to-a-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!