Search code examples
c#ajaxjsonasp.net-web-apihttp-get

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?


I have the following complex object in JavaScript which contains filter options

var filter={caseIdentifiter:'GFT1',userID:'2'};

which I want to pass to an ASP.NET MVC4 WebApi controller GET

[HttpGet]
public IEnumerable<JHS.Repository.ViewModels.CaseList> Get([FromBody]Repository.InputModels.CaseListFilter filter)
{
  try
  {
    return Case.List(filter);
  }
  catch (Exception exc)
  {
    //Handle exception here...
    return null;
  }
}

using an jQuery ajax call

var request = $.ajax({
  url: http://mydomain.com/case,
  type: 'GET',
  data: JSON.stringify(filter),
  contentType: 'application/json; charset=utf-8',
  cache: false,
  dataType: 'json'
});

The "filter" object in the ASP.NET controller method is "null". If I change it to a POST the filter object is passed correctly. Is there a way to pass a complex object to a GET?

I do not want to separate out the parameters to the URL as there will be a number of them which would make it inefficient, it would be hard to have optional parameters, and this way the method signature stays constant even if new parameters are added.


Solution

  • After finding this Stack Overflow question/answer

    Complex type is getting null in a ApiController parameter

    the [FromBody] attribute on the controller method needs to be [FromUri] since a GET does not have a body. After this change the "filter" complex object is passed correctly.