Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an array as a querystring in a GET request by using JQuery AJAX

In my javascript application I am trying to pass an array of strings, among other parameters, in a GET request to an ASP.NET Web API REST service by using jQuery Ajax. An example URL is as follows:

http://my.services.com/products?userId=1abc&id=1&id=2&id=3

The signature of the Web API method:

[HttpGet("products")]
public IActionResult GetProducts(string userId, int[] id)

If I try the request with Postman the binding of the parameters works correctly. In the Javascript app I tried several solutions with no luck. The code is as follows:

let data = {
  'userId': '1abc'
  'id': [1,2,3]
}

$.ajax({
   type: 'get',
   url: 'http://my.services.com/products',
   data: data,
   crossDomain: true, //CORS
   cache: false,
}

In this case the URL becomes:

http://my.services.com/products?userId=1abc&id%5B%5D=1&id%5B%5D=2&id%5B%5D=3

since in the parsed result instead of using id as key, it uses id[], therefore codifies the characters [] as %5B and %5D.

No luck even if I use this code:

let data = {
  'userId': '1abc'
  'id': JSON.stringify([1,2,3])
}

or (as seen in this answer)

let data = {
  'userId': '1abc'
  'id[]': [1,2,3]
}

Keep in mind that for the other calls the code JQuery AJAX code above works without any issue.

like image 407
CiccioMiami Avatar asked Aug 29 '18 09:08

CiccioMiami


1 Answers

The problem with the request is because the default ASP.Net model binder expects arrays to be sent through the querystring as separate key/value pairs, as your first example URL shows.

To achieve this you simply need to set traditional: true in your jQuery $.ajax() request:

let data = {
  userId: '1abc'
  id: [ 1, 2, 3 ]
}

$.ajax({
  type: 'get',
  url: 'http://my.services.com/products',
  data: data,
  traditional: true
});

Also, as a side note, be wary of using absolute URLs when making AJAX requests, you can easily encounter CORS issues if the code isn't maintained routinely. I'd suggest using relative paths where possible.

like image 197
Rory McCrossan Avatar answered Nov 14 '22 23:11

Rory McCrossan