Skip to main content
 首页 » 编程设计

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

2024年01月31日33lvdongjie

我的 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... 
    } 
});