3

I have this Web API method:

[Route("api/[controller]")]
[ApiController]
public class SubjectsController : ControllerBase
{
    [HttpGet("children")]
    public IActionResult GetAllFromChildren([FromQuery]int[] childrenIds)
    {
        // omitted for brevity
    }
}

I'm trying to call this via Ajax passing in an query string but I can't seem to get it to work. My Ajax call looks like this:

$.ajax({
    url: "/api/subjects/children?childrenIds=1&childrenIds=2&childrenIds=3",
    method: "GET",
    contentType: "application/json; charset=utf-8"
})

The method is called but it the int array does not get populated. What am I doing wrong?

Askolein
  • 3,250
  • 3
  • 28
  • 40
g_b
  • 11,728
  • 9
  • 43
  • 80
  • 1
    It was a typo from me, I will edit in the question, I checked the code and there is a &. – g_b Aug 23 '18 at 14:22
  • Does this answer your question? [Pass an array of integers to ASP.NET Web API?](https://stackoverflow.com/questions/9981330/pass-an-array-of-integers-to-asp-net-web-api) – Michael Freidgeim Oct 25 '20 at 20:17

1 Answers1

8

Try add Name to [FromQuery], so the code should look like this:

[Route("api/[controller]")]
[ApiController]
public class SubjectsController : ControllerBase
{
    [HttpGet("children")]
    public IActionResult GetAllFromChildren([FromQuery(Name="childrenIds")]int[] childrenIds)
    {
        // omitted for brevity
    }
}

and ajax url like this:

$.ajax({
    url: "/api/subjects/children?childrenIds=1&childrenIds=2&childrenIds=3",
    method: "GET",
    contentType: "application/json; charset=utf-8"
})
kml
  • 280
  • 1
  • 2
  • 9