[英]Javascript send an input as array to a C# WebAPI
- - - - - - - - - - - - -编辑 - - - - - - - - - - - - --------
这不是重复的,因为我不能使用关于这个问题的ajax请求。
我正在用javascript创建一个表单来调用ac#WebApi,它将返回一个xls文件(这就是为什么我正在创建一个表单而不是ajax调用)。 webApi必须接收一个整数数组,该数组将对应于对象ID列表。 webApi是以下
[Route("getExcel")]
[HttpPost]
public HttpResponseMessage getExcel([FromBody]int[] ids)
{
...
}
我要建立的表格是这样的:
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();
该ids
对的WebAPI是空的(但不是null)......当小提琴手看,原始视图显示了这种ids=15&ids=14&ids=13&ids=12&ids=11
,这正是我需要的...为什么没有关联使用WebApi ID? 如果我的网址发送精确值(和改变[FromBody]
至[FromUri]
它的工作原理...
- - - - - - - - - -编辑 - - - - - - - - - - - - - - -
这是调用该方法时WebApi上数组ids
中的内容: ids {int[0]}
(在调试时看到)
因此,解决方案是在后端创建一个这样的模型:
public class ExcelIds
{
public int[] ids { get; set; }
}
并将控制器更改为:
[Route("getExcel")]
[HttpPost]
public HttpResponseMessage getExcel([FromBody]ExcelIds model)
{
//code here
}
您可以使用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.