You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何jQuery向Razor页面传递ID列表失败?控制台显示正常

问题

在ASP.NET Razor页面开发中,使用jQuery Ajax向Razor页面传递ID列表时,浏览器控制台能正确显示包含两个元素的数组,但Razor页面的OnGetListIdUpdated方法中接收的List<int> selectedIds为null。

相关代码

后端C#代码

public JsonResult OnGetListIdUpdated(List<int> selectedIds)
{
    return new JsonResult(selectedIds);
}

前端JavaScript代码

$(document).ready(function () {

    $('#reprintdatabtn').click(function (event) {
        event.preventDefault();
          var selectedIds = [];
        $("input[name='chkSel']:checked").each(function() {
            var id = $(this).closest("tr").find("td:last").text();
            if (id !== "") {
                selectedIds.push(parseInt(id));
            }
        }); 
        console.log(selectedIds);
        $.ajax({
            url: '?handler=ListIdUpdated',
            type: "GET",
            dataType: "json",
            data: { selectedIds: selectedIds },


            success: function (response) {
                $("#lblRowsCount").html(response.counter);
                $('#msgstatus').text(response.messageStatus);
                // Handle the server response here
            }
        });
    });
});

浏览器控制台输出

[
    16810,
    16811
]

原因与解决方法

原因

GET请求中,jQuery默认会把数组参数格式化为selectedIds[]=16810&selectedIds[]=16811,但ASP.NET Razor页面的模型绑定器默认不识别这种带方括号的参数命名格式,导致无法正确绑定到List<int>参数,最终参数为null。

解决方法

有两种可行的处理方式:

  1. 修改jQuery的参数序列化方式
    在Ajax请求中添加traditional: true配置,让jQuery按照传统方式序列化数组,参数会变成selectedIds=16810&selectedIds=16811,ASP.NET的模型绑定器可以正确识别:

    $.ajax({
        url: '?handler=ListIdUpdated',
        type: "GET",
        dataType: "json",
        traditional: true, // 添加该配置
        data: { selectedIds: selectedIds },
        success: function (response) {
            $("#lblRowsCount").html(response.counter);
            $('#msgstatus').text(response.messageStatus);
        }
    });
    
  2. 手动构造查询字符串
    自行拼接符合ASP.NET要求的参数格式,规避jQuery的默认序列化逻辑:

    // 构造符合要求的查询参数
    var queryParams = selectedIds.map(id => `selectedIds=${id}`).join('&');
    $.ajax({
        url: `?handler=ListIdUpdated&${queryParams}`,
        type: "GET",
        dataType: "json",
        success: function (response) {
            $("#lblRowsCount").html(response.counter);
            $('#msgstatus').text(response.messageStatus);
        }
    });
    

内容的提问来源于stack exchange,提问作者ahmed abdelaziz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 03:07:25