0

I have an array of id's in JS, like so

var ids = [123,456,789]

I am trying to pass them as part of a querystring in a GET request to a .NET API application. From what I understand .NET needs the querystring to resemble endpoint/ids=123&ids=345&ids=789 or similar.

I've tried using $.param({ ids: ids } ) but it ends up as ids%5B%5D=123&ids%5B%5D=456&ids%5B%5D=789

How can I do this?

Here's my html link to use it. I'm using knockout databinding and observables

<a class="btn btn-sm btn-default" data-bind="attr:{'href':'bill/' + bills().map((data) => {return data.billId;}), 'target':'_blank'}">
  <i class="fa fa-print"></i> 
  Click
</a>

and it currently returns bill/123,456,789

Colonel Mustard
  • 1,482
  • 2
  • 17
  • 42
  • 2
    While would query string have duplicate keys? – guest271314 Oct 20 '17 at 15:25
  • It would help a lot to see your full JS and HTML here. It looks like you need to use `traditional: true` on the AJAX call – Rory McCrossan Oct 20 '17 at 15:26
  • @guest271314 that's how the MVC/WebAPI the ModelBinder does it. PHP generally uses `foo[]=1,2,3`, MVC does `foo=1&foo=2&foo=3` – Rory McCrossan Oct 20 '17 at 15:26
  • It's not .NET that "needs" anything. What you posted is simply an encoded URL query string. Did you encounter a problem? – Panagiotis Kanavos Oct 20 '17 at 15:27
  • @RoryMcCrossan most certainly not. That what *Javascript* generates. Both PHP and MVC run on the *server*. And you *can't* pass `foo[]=1,2,3` in a URL – Panagiotis Kanavos Oct 20 '17 at 15:28
  • added the html that shows the href being generated – Colonel Mustard Oct 20 '17 at 15:31
  • @PanagiotisKanavos I'm not sure the point you're making, especially with your painfully obvious 'PHP and MVC run on the server' comment, but it seems you've misunderstood what I'm saying. Here's a clearer explanation than I can make in a comment: https://www.codeproject.com/Articles/701182/A-Custom-Model-Binder-for-Passing-Complex-Objects. See the first few paragraphs re. binding querystring fields to complex objects. – Rory McCrossan Oct 20 '17 at 15:38

1 Answers1

0

You could use

ids.map(ids=> `ids=${id}`).join('&')

to create a string with ids=123&ids=345&ids=789. Aftwards you can just add the concattedIds to you url.

Would be something like this:

<a class="btn btn-sm btn-default" data-bind="attr:{'href':'bill/' + bills().map((data) => `ids=${data.billId}`).join('&'), 'target':'_blank'}">
  <i class="fa fa-print"></i> 
  Click
</a>
sn_92
  • 488
  • 3
  • 11