简体   繁体   中英

Javascript send an input as array to a C# WebAPI

-------------------------EDIT--------------------------------

It's not a duplicate because I can't use an ajax Request, as asked on this question.


I'm creating a form in javascript to call ac# WebApi that will return a xls file (that's why I'm creating a form and not an ajax call). The webApi must receive an array of integer, that will correspond to a list of ids of objects. The webApi is the following

[Route("getExcel")]
[HttpPost]
public HttpResponseMessage getExcel([FromBody]int[] ids)
{
...
}

the form I'm building is like this:

var form = document.createElement("form");
form.setAttribute('method', "post");
setAttribute('action', baseUrl + "api/processos/getExcel");
form.setAttribute('target', "_blank");
var rows = $("#tbl").dataTable().fnGetNodes();
var arr = [];
for (var i = 0; i < rows.length; i++)
{
  ids = $("#tbl").dataTable().fnGetData(i).processosId; 
  var input = document.createElement("input");
  input.setAttribute('type', "text");
  input.setAttribute('name', "ids[]");
  input.setAttribute('value', ids);
  form.appendChild(input);
}
document.body.appendChild(form);
form.submit();

The ids on the WebApi is empty (but not null)... When watching on Fiddler, the Raw View shows this ids=15&ids=14&ids=13&ids=12&ids=11 which is exactly what I need... Why isn't associating with the WebApi ids ? If I send that exact values in the URL (and changing the [FromBody] to [FromUri] it works...

-------------------EDIT------------------------------

this is what is in the array ids on the WebApi when the method is called: ids {int[0]} (as seen while debugging)

So, the solution is to create a model on the backend such this:

public class ExcelIds
{
    public int[] ids { get; set; }
}

and change the controller to:

[Route("getExcel")]
[HttpPost]
public HttpResponseMessage getExcel([FromBody]ExcelIds model)
{
    //code here
}

You could use FormDataCollection.GetValues(string Key) to get an array of strings, that you could later convert to int[].

[Route("getExcel")]
[HttpPost]
public HttpResponseMessage getExcel(FormDataCollection data)
{
   string[] ids = data.GetValues("ids");
   ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM