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

Ajax传递参数数组至控制器时参数值异常的问题排查

问题:AJAX调用局部视图时参数无法正确传递到控制器

我想编写一个通用函数来调用参数数量和类型各不相同的局部视图,但无法将参数正确传递至控制器。页面构建参数数组的代码如下:

$('#btn_New').on('click', function () {
    var params = {};
    params.index = count;
    
    CallAddPartial(params, "?handler=NewPeriodPartial", "tbl_Periods");
    count++;
});

通用函数能正常接收参数数组,但控制器获取的index始终为0,函数代码如下:

function CallAddPartial(paramsArray, handler, tbl) {
    $.ajax({
        type: "GET",
        url: handler,
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: JSON.stringify(paramsArray),
        success: function (response) {
            $('#' + tbl +' tr:last').after(response);
        },
        failure: function (response) {
            alert(response.responseText);
        },
        error: function (response) {
            alert(response.responseText);
        }
    });
}

控制器代码:

public PartialViewResult OnGetNewPeriodPartial(int index)
{
    return Partial("NewPeriod", new Periods.NewPeriodModel(_context, index));
}

我期望index能获取到count的数值,尝试过使用和不使用JSON.stringify,也尝试过接收字符串类型,但均无效。


解决方案

问题核心在于GET请求的参数传递方式错误,修改通用函数即可解决:

function CallAddPartial(paramsArray, handler, tbl) {
    $.ajax({
        type: "GET",
        url: handler,
        dataType: 'html',
        data: paramsArray,
        success: function (response) {
            $('#' + tbl +' tr:last').after(response);
        },
        failure: function (response) {
            alert(response.responseText);
        },
        error: function (response) {
            alert(response.responseText);
        }
    });
}

关键修改点说明:

  1. 移除contentType: "application/json; charset=utf-8":GET请求不需要设置这个头,它是POST请求发送JSON请求体时才需要的配置。
  2. 直接传递paramsArray对象:jQuery会自动将对象序列化为index=xxx格式的查询参数,控制器能直接绑定到同名参数上。
  3. 将dataType改为html:控制器返回的是局部视图的HTML内容,而非JSON,之前的json类型会导致解析错误。

额外排查建议:

  • 调用CallAddPartial前,用console.log(count)确认变量值是否正确递增。
  • 确保控制器方法的参数名index和前端传递的参数名完全一致。

内容的提问来源于stack exchange,提问作者Rose-marie Paradis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 21:45:34