Pass an array of strings as data in jquery ajax in web api

I am trying to pass a string array to the Web Api method, which takes an array of strings as an argument. Run my web api method

[HttpGet] public string HireRocco(string[] hitList) { string updateList = string.Empty; return updateList; } 

My ajax

 var uri = 'http://localhost:16629/api/AssassinApi/HireRocco', hitList = ['me', 'yourself']; $.ajax({ url: uri, type: 'GET', data: { hitList : hitList }, cache: false, dataType: 'json', async: true, contentType: false, processData: false, success: function (data) { }, error: function (data) { } }); 

The above ajax successfully gets into the HireRocco method, but the hitList parameter is still zero. What should I change to pass an array of strings as a parameter.

+5
source share
3 answers

If you need to send data via HttpGet , you can add [FromUri] , you can change the action of your controller as follows, and your JavaScript should work like this:

 [HttpGet] public string HireRocco([FromUri] string[] hitList) { string updateList = string.Empty; return updateList; } 
+3
source

Remove the contentType: false , then set the processData parameter to true so that it can add postData to your url, as it works with the receive request, or you will need to change the api to accept the POST request, which is set via the header.

 $.ajax({ url: uri, type: 'GET', data: { hitList : hitList }, cache: false, dataType: 'json', async: true, processData: true, success: function (data) { console.log(data); }, error: function (data) { } }); 
0
source

First of all, I suggest using POST, not GET. create a javascript array. insert the data inside it. send it to the action web api method using JSON.Stringify .. and then process further logic.

In the web api, create a model variable .. and create a list object.

Below is the code.

Javascript

 var demoarray=[]; demoarray.push({"test1":"hi", "test2":"hello"}); //test1 and test2 are model variable names in web api and hi and hello are their values 

you can repeat the process in a for loop or something to add multiple values.

  $.ajax({ url:"http://localhost..", type: "POST", data: JSON.Stringify(demoarray), contentType: "application/json", success: function(data) { }, error: function(data) { } }); 

WEB API Code Create a Model Class and Two Properties

 public string test1 {get; set;} public string test2 {get; set;} 

controller code

 [Httppost] public void actionmethod(List<modelclass> obj) { int i=0; for(i=0; i<obj.count; i++) { //your logic } } 
0
source

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


All Articles