【问题标题】:Get null parameter in the server side after ajax callajax调用后在服务器端获取空参数
【发布时间】:2023-03-19 12:17:01
【问题描述】:

我的 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. 如何修复我的代码?

【问题讨论】:

  • async: false 不要这样做。

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


【解决方案1】:

谢谢大家,

我通过像这样编辑我的代码来修复我的代码:

$.ajax({
        type: "post",
        async:false,
        url: "/api/Demande/ReservationAgendaByDrivers",
        data: JSON.stringify(arr), 
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
        .......
                                 }
       });

【讨论】:

    【解决方案2】:

    这个错误的原因是什么?

    int[] tab 期望在名为 tab 的参数中有一个 var,当您尝试发送数组 arr 时,该变量不存在。

    如何修复我的代码?

    在数据中发送一个对象:

    data: { tab: arr }, // here tab is the key which belongs to int[] tab at backend
    

    async:false 不是将其设置为 false 的好选择。这不应该用于将其设置为 false,因为有一些方法可以使用 promises 正确执行这些操作。

    【讨论】:

    • 我进入服务器端:tab = {int[0]}
    • 您需要更改已发布的 ajax 中的数据参数。您是否尝试使用data: { tab: arr }, 发送它,请在此处注意tab 这个词。
    • 我按照你说的修改了我的代码,tab参数现在不是null而是一个空数组!!!
    • @LamloumiAfif 那么我想看看你是如何制作数组或推送数组中的值的。
    • if (checkarray[i] == 1) arr.push(ids[i]); 因此它只推送数组中的一项。
    【解决方案3】:
    console.log(arr);
    $.ajax({
        type: "post",
        url: "/api/Demande/ReservationAgendaByDrivers", 
        data:{tab:arr},
        success: function (data) {
       .............
                                 }});
    

    【讨论】:

    • 我进入服务器端:tab = {int[0]}
    【解决方案4】:

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

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

    【讨论】:

    • 我进入服务器端:tab = {int[0]}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-14
    • 2019-07-09
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多