Passing lists from jQuery to a service

I'm sure I did it in another solution, but I can't find a solution to do it again, and wondered if anyone could help me ...

This is my WebAPI code:

public class WebController : ApiController { public void Get(string telephone, string postcode, List<Client> clients) { } } 

And by calling this from jQuery:

  function Client(name, age) { this.Name = name; this.Age = age; } var Clients = []; Clients.push(new Client("Chris", 27)); $.ajax({ url: "/api/Web/", data: { telephone: "999", postcode: "xxx xxx", clients: Clients } }); 

But the clients object always returns as null. I also tried JSON.stringify(Clients) and this is the same result. Can someone see something obvious, I'm missing here?

+4
source share
1 answer

The binding of the action parameter in the web API is different from ASP.NET MVC (you can learn more about this in this article ):

  • "simple" types (string, int, etc.) are associated with a URI
  • "complex" types are associated with the request body

If you do not want to follow the conventions, you need to mark your parameters using the [FromBody] or [FromUri] , depending on where you want to link them.

In your case, since you are using a GET request, you need to mark your clients parameter with [FromUri] for the correct binding:

 public class WebController : ApiController { public void Get(string telephone, string postcode, [FromUri]List<Client> clients) { } } 
+4
source

Source: https://habr.com/ru/post/1442409/


All Articles