[英]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. 这不是重复的,因为我不能使用关于这个问题的ajax请求。
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). 我正在用javascript创建一个表单来调用ac#WebApi,它将返回一个xls文件(这就是为什么我正在创建一个表单而不是ajax调用)。 The webApi must receive an array of integer, that will correspond to a list of ids of objects.
webApi必须接收一个整数数组,该数组将对应于对象ID列表。 The webApi is the following
webApi是以下
[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 ? 该
ids
对的WebAPI是空的(但不是null)......当小提琴手看,原始视图显示了这种ids=15&ids=14&ids=13&ids=12&ids=11
,这正是我需要的...为什么没有关联使用WebApi ID? If I send that exact values in the URL (and changing the [FromBody]
to [FromUri]
it works... 如果我的网址发送精确值(和改变
[FromBody]
至[FromUri]
它的工作原理...
-------------------EDIT------------------------------ - - - - - - - - - -编辑 - - - - - - - - - - - - - - -
this is what is in the array ids
on the WebApi when the method is called: ids {int[0]}
(as seen while debugging) 这是调用该方法时WebApi上数组
ids
中的内容: ids {int[0]}
(在调试时看到)
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[]. 您可以使用
FormDataCollection.GetValues(string Key)
获取一个字符串数组,以后可以将其转换为int []。
[Route("getExcel")]
[HttpPost]
public HttpResponseMessage getExcel(FormDataCollection data)
{
string[] ids = data.GetValues("ids");
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.