Javascript 将输入作为数组发送到 C# WebAPI
Javascript send an input as array to a C# WebAPI
>-------------------------EDIT
--------------------------------这不是重复的,因为我不能使用ajax请求,正如这个问题所问的那样。
我正在javascript中创建一个表单来调用将返回xls文件的c# WebApi(这就是我创建表单而不是ajax调用的原因(。webAPI 必须接收一个整数数组,该数组对应于对象的 id 列表。网络接口如下
[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();
WebApi 上的ids
为空(但不是空(...在小提琴手上观看时,原始视图显示了这个ids=15&ids=14&ids=13&ids=12&ids=11
这正是我所需要的......为什么不与 WebApi ID 关联? 如果我在 URL 中发送确切的值(并将[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");
...
}
相关文章:
- 如何在映射数组中添加换行符
- javascript结合了数组和字典
- 需要帮助设置json数组
- 不能从angular2中的子组件指定父组件中的数组
- 使用JS将数组转换为json对象
- 数组在递归方法中设置为null
- knockoutjs可观察数组
- Javascript-如何读取json文件中的列并将其保存在Javascript数组中
- 将数组从PHP传递到Javascript
- JavaScript数组排序(函数)用于对表行进行排序,而不是排序
- 在函数中添加数组元素的数值
- 无法通过数组映射绑定
- javascript中的数组出错
- 如何使用 node.js 比较两个 json 数组
- Javascript(Angular)从一个对象数组到第二个数组查找值
- 根据id将json数组组合为一个json数组
- 如何通过数组更新角度子范围
- 有没有一种方法可以添加相同的项目val=“0”;4〃;到JavaScript中数组的每个对象
- webapi获胜't使用$.param反序列化字符串数组
- 在json中传递base64字节的图像数组给webApi