javascript - 将空数组发送到 webapi

标签 javascript c# jquery asp.net asp.net-web-api

我想将一个空的 javascript 数组 [] 发布到 webAPI 并让它创建一个空的整数列表。我也想要它,所以如果我将 javascript null 发布到 webAPI,它将 null 分配给整数列表。

JS:

var intArray = [];
$.ajax({
    type: 'POST',
    url: '/api/ListOfInts',
    data: {'' : intArray},
    dataType: 'json'
});

C# 网络接口(interface)

[HttpPost]
public void ListOfInts([FromBody]List<int> input)

问题 1) Jquery 拒绝发送数据 {'' : []} 作为 post payload。只要我在数组中添加一些东西,它就会工作,例如 {'' : [1,2,3]}

问题 2) Passing empty js array to controller gives null根据我阅读的内容,即使我确实让它发布一个空数组,它也会将列表初始化为 null。讨论过的解决方案使列表始终初始化为空,但我不希望这样。我希望它在某些情况下为 null(当向它发送 null/undefined 时)并且当 [] 被发送时它应该初始化为空。

编辑:参见 https://www.asp.net/web-api/overview/advanced/sending-html-form-data-part-1关于我为什么使用 {'' : []}

最佳答案

使用 JSON.stringify(intArray)contentType: 'application/json' 对我有用:

$.ajax({
     url: "/api/values",
     method: "POST",
     contentType: 'application/json',
     data: JSON.stringify([])
});

enter image description here

$.ajax({
     url: "/api/values",
     method: "POST",
     contentType: 'application/json',
     data: null
});

enter image description here

$.ajax({
      url: "/api/values",
      method: "POST",
      contentType: 'application/json',
      data: JSON.stringify([1, 2, 3])
});

enter image description here

关于javascript - 将空数组发送到 webapi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37688726/

相关文章:

javascript - 为什么 Fetch API 将第一个 PUT 请求作为 OPTIONS 发送

c# - Telegram bot - 向/启动命令添加唯一键

c# - 升级到 SignalR 1.0.0 alpha2 时未触发 OnConnected 任务

c# - 实现属性或实现子类

javascript - 从 Json 生成 Jquery Mobile 站点

javascript - 深度克隆 Backbone.js 模型

javascript - 语法错误,在 jQuery 选择器中检查了无法识别的表达式 : !

javascript - 禁用/重新启用 javascript webui-popover 时遇到问题

javascript - 无限期动画结束事件?

jquery - 查找元素是否隐藏