wickjon
wickjon

Reputation: 920

MVC web api GET parameter is always null

Following is my ajax call

                     $.ajax({
                     type: "GET",
                     url: "https://localhost/api/Client",
                     data:        JSON.stringify({"SortExpression":"clientName","SortDirection":"desc"}),
                     contentType: "application/json; charset=utf-8",
                     async: false,
                     cache: false,
                     dataType:'json',
                     error: function (data) {
                             alert("hi error buddy")
                     },
                     success: function (response) {
                         if (response) {
                           //todo
                         }
                     }
                 });

And my controller

public List<Customer> Get([FromUri] SortFilter filter)
    {

    }

and my model

public class SortFilter
{
    public string SortExpression
    {
        get; set;
    }
    public string SortDirection
    {
        get;  set;
    }
}

but my contoller always takes the parameters as NULL. where am I going wrong ?

Upvotes: 0

Views: 1194

Answers (2)

James Bunch
James Bunch

Reputation: 1

GET requests are performed on the query string, which should not be JSON encoded. POST, and PUT data may be JSON encoded, but not GET. The reason your parameter is null is because the query string is a single string with no parameter name.

replace:

data:JSON.stringify({"SortExpression":"clientName","SortDirection":"desc"})

with

data:{"SortExpression":"clientName","SortDirection":"desc"}

You can check the WebAPI call directly by typing in the full URL to the web API method

https://localhost/api/Client?SortExpression=clientName&SortDirection=desc

This will allow you to debug your data retriever, and page separately which should make the whole process much easier.

Upvotes: 0

David
David

Reputation: 218798

You're supplying a value, but not a key. So while the model binder may be able to discern what a SortFilter is, it has no way of knowing what filter is.

Try wrapping the object and giving it a key name. Perhaps something like this:

JSON.stringify({"filter":{"SortExpression":"clientName","SortDirection":"desc"}})

Upvotes: 2

Related Questions