Please refer to this link from MVC:
I am having trouble with model binding. From JavaScript I do an GET Ajax request to my API end point called "/api/products" passing in some parameters including paging and sorting as query parameters. Here is the plete URI:
http://localhost/api/products?page=1&count=10&filter[name]=Test1&filter[price]=10&sorting[name]=desc
On the server side, I have an Web API controller accepting these properties from the URI:
public async IHttpActionResult Get([FromUri]Dictionary<string,string> filter, [FromUri]Dictionary<string,string> sorting, int count, int page)
{
//...
}
The "count" and "page" parameters bind perfectly fine, and the filter and sorting binds as an instance of a dictionary, but its count is 0.
I got this working in MVC but it doesn't seem to be doing the truck in Web API.
Please refer to this link from MVC: http://aspnetwebstack.codeplex./discussions/351011
I am having trouble with model binding. From JavaScript I do an GET Ajax request to my API end point called "/api/products" passing in some parameters including paging and sorting as query parameters. Here is the plete URI:
http://localhost/api/products?page=1&count=10&filter[name]=Test1&filter[price]=10&sorting[name]=desc
On the server side, I have an Web API controller accepting these properties from the URI:
public async IHttpActionResult Get([FromUri]Dictionary<string,string> filter, [FromUri]Dictionary<string,string> sorting, int count, int page)
{
//...
}
The "count" and "page" parameters bind perfectly fine, and the filter and sorting binds as an instance of a dictionary, but its count is 0.
I got this working in MVC but it doesn't seem to be doing the truck in Web API.
Share Improve this question edited Apr 25, 2015 at 23:03 TylerH 21.1k79 gold badges79 silver badges114 bronze badges asked Apr 8, 2014 at 17:40 Fanie ReyndersFanie Reynders 5804 silver badges16 bronze badges 1- Check the solution proposed at stackoverflow./questions/11950351/… – Veverke Commented Apr 22, 2015 at 12:09
3 Answers
Reset to default 4You can still leverage out of the box default model binder and your uri would look like
http://localhost/api/products?page=1&count=10&filter[0].key=name&filter[0].value=Test1&filter[1].key=price&filter[0].value=10&sorting[0].key=name&sorting[0].value=desc
I think it is better to use a model as parameter, such as:
Public class model
{
Public Dictionary<string,string> filter{get;set;}
Public Dictionary<string,string> sorting{get;set;}
Public int sorting{get;set;}
}
public async IHttpActionResult Get(model yourModel)
{
//...
}
You could use a JSON string to keep the url short. The URI would be like
http://localhost/api/products?filter={"name":"Test","price":10}
Web API controller:
public void Get(string filter)
{
var filterDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(filter);
//...
}