7

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.

1 Answer 1

18

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your solution, it works, I didn't know about this traditional parameter. I edited my question since the syntax issue was a typo I made during the copy/pasting the code.
No problem, glad to help. I removed the note about the syntax :)
Note for all the people use other backends (like Drupal, PHP): use traditional: false (default).
For those wondering what traditional is for like me: api.jquery.com/jQuery.param

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.