C # WebApi Parameter Request Parameter

I have a query string coming from a jquery grid that I am trying to parse into parameters in C # Web API, but I cannot get one of the properties to populate.

Query line:

?current=1&rowCount=10&sort[received]=desc&sort[email]=asc&sort[id]=desc&searchPhrase=

      

Method:

public IEnumerable<IUserDto> Get(int current, int rowCount, NameValueCollection sort, string searchPhrase)

      

The 'sort' parameter is always zero, all others are filled in correctly. I've tried several types for the parameter, but no matter what I tried, I always get a null parameter.

Any direction or suggestion on the type of parameter would be appreciated.

+3


source to share


1 answer


If you want to deserialize a complex aggregate value, for example NameValueCollection

from a query string, you need to decorate the parameter with FromUriAttribute

. This does not guarantee that it will work in any way, but otherwise it will not work unless you define a custom parameter handler.

public IEnumerable<IUserDto> Get(
    int current,
    int rowCount,
    [FromUri] NameValueCollection sort,
    string searchPhrase
) { ... }

      

Also, you need to make sure that what you are serializing to your URL is in fact a JSON dictionary. From the url you posted it looks like you are adding properties received

, id

and email

from the local object as separate query string parameters

&sort[received]=desc&sort[email]=asc&sort[id]=desc

      



Binding WebAPI parameters will not automatically aggregate them into a dictionary for you.

You can build it like

var sortParam = ['received', 'id', 'email'].reduce(function (o, key) {
  o[key] = sort[key];
  return o;
}, {});

var queryParams = '?current=' + 1 + 
                  '&rowCount' = 10 + 
                  '&sort=' + JSON.stringify(sortParam) +
                  '&searchPhrase=' + something;

      

I would also suggest changing the order to the last parameter sort

.

0


source







All Articles