c# - ajax调用后在服务器端获取空参数

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

我的 ASP.Net WebApi 应用程序中有一个奇怪的问题。我有这个客户端代码:

 var arr = [];
for (var i = 0; i < checkarray.length; i++) {
    if (checkarray[i] == 1) arr.push(ids[i]);
}
console.log(arr);
$.ajax({
    type: "post",
    async: false,
    url: "/api/Demande/ReservationAgendaByDrivers", 
    data: arr,
    success: function (data) {
        // ...
    }
});

在服务器端:

[HttpPost]
public IEnumerable<ReservationModel> ReservationAgendaByDrivers(int[]  tab)
{
    List<ReservationModel> outlst = new List<ReservationModel>();
    List<ReservationModel> model = GetListReservation().ToList();
    foreach (ReservationModel item in model)
    {
        if (!item.id_chauffeur.HasValue) 
            continue;

        if (tab.Contains(item.id_chauffeur.Value)) 
            outlst.Add(item);
    }
    return outlst.OrderByDescending(x => x.id_demande);
}

例如,作为浏览器的输出,我得到这个数组:

[7, 5, 1]

但是服务器端的tab参数总是null!!

我需要知道:

  1. 这个错误的原因是什么?
  2. 如何修复我的代码?

最佳答案

要使 ModelBinder 正常工作,您需要在 tab 属性下的对象中提供数组。您还应该删除 async: false,因为使用它是无法形容的坏习惯

$.ajax({
    type: "post",
    url: "/api/Demande/ReservationAgendaByDrivers", 
    data: {
        tab: arr
    },
    success: function (data) {
        // handle the response here...
    }
});

关于c# - ajax调用后在服务器端获取空参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33889360/

相关文章:

c# - 在 C# 中使用 Linq 匹配 2 个集合之间的元素

c# - 当我倒退时第三人称镜头卡顿

jQuery 在 IE8 中不起作用?

c# - CORS 不工作 ASP.Net MVC5

c# - 悬停时菜单跳转

c# - json 和 eval 的问题

javascript - 如何用jquery裁剪图像?

javascript - 如何拖放到文本中

c# - 查询字符串唯一字符串生成器?

c# - jQuery Ajax 对 Web 服务的调用似乎是同步的