How to pass an array of objects to a webAPI list

I have some basic HTML that calls a WebAPI function using jQuery ajax call. HTML sends an array of objects that must be mapped to a function parameter, which I get as a LIST. If I delete the array and send only 1 object, and also delete the list from the function, then my code works and the object is successfully passed to the parameter.

JavaScript code below

function Call_Service () { var input = { STATUS: "MY New Status", CATEGORY: "My Value" }; var input2 = { STATUS: "MY New Status2", CATEGORY: "My Value2" }; var input_array = new Array(); input_array[0] = input; input_array[1] = input2; $.ajax({ type: "POST", url: "http://localhost:34989/api/TMSPortal/objectPOC", data: input_array, success: function (response) { alert(response); } }); } 

C # WebAPI is below

  public Int64 objectPOC(List<TMS_STATUS> _Status) { Int64 retValu = 0; for (int i = 0; i < _Status.Count; i++) { retValu++; } return retValu; } 
+1
source share
2 answers

As I found out, the web API currently does not allow more than one complex parameter, so I did my work as follows. Let me know if anyone has a better solution:

Web-API function changed to get JObject, and then my complex objects were extracted from it. Web API functions are as follows:

  public Int64 objectPOC(JObject jsonWrapper) { dynamic jsonValues = jsonWrapper; JArray jsonInput = jsonValues.input; JArray jsonInput2 = jsonValues.input2; List<TMS_STATUS> _Status = jsonInput.ToObject<List<TMS_STATUS>>(); List<TMS_STATUS> _Status2 = jsonInput2.ToObject<List<TMS_STATUS>>(); Int64 retValu = 0; for (int i = 0; i < _Status.Count; i++) { retValu++; } return retValu; } 

Ajax Call is as follows:

  function Call_Service () { var input = { STATUS: "MY New Status", CATEGORY: "My Value" }; var input2 = { STATUS: "MY New Status2", CATEGORY: "My Value2" }; var input_array = new Array(); input_array[0] = input; input_array[1] = input2; alert(input_array[0].STATUS); $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "http://localhost:34989/api/TMSPortal/objectPOC", dataType: "json", data: JSON.stringify({ input: input_array, input2: input_array }), success: function (response) { alert(response); } }); } 
+3
source

To send multiple parameters of a complex type, create a model and publish them as properties inside the model. In the Web API, you can only have one input parameter of a complex type out of the box.

0
source

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


All Articles