Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 401
ChrisP Avatar asked Apr 04 '13 14:04

ChrisP


People also ask

How do you pass complex objects in GET Request Web API?

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".

Can we pass complex object in GET request?

You can pass it as a stringified json or use the request body via post instead of get.


2 Answers

After finding this StackOverflow 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.

like image 124
ChrisP Avatar answered Sep 28 '22 02:09

ChrisP


If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.

//javascript file  var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" }; var request = JSON.stringify(data); request = encodeURIComponent(request);  doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {     window.console.log(result); });  //webapi file: [HttpGet] public ResponseResult StartProcess() {     dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);         int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);     Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);     int userID = int.Parse(queryJson.UserID.Value);     string userName = queryJson.UserName.Value; }  //utility function: public static dynamic ParseHttpGetJson(string query) {     if (!string.IsNullOrEmpty(query))     {         try         {             var json = query.Substring(7, query.Length - 7); //seperate ?data= characters             json = System.Web.HttpUtility.UrlDecode(json);             dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);              return queryJson;         }         catch (System.Exception e)         {             throw new ApplicationException("can't deserialize object as wrong string content!", e);         }     }     else     {         return null;     } } 
like image 45
Bes Ley Avatar answered Sep 28 '22 04:09

Bes Ley