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

为何jQuery传递给Controller方法的参数非空却显示为Null?

解决jQuery AJAX调用Controller方法参数为Null的问题

我来帮你排查下这个参数传null的问题哈,这种情况我碰到过好几次,主要是GET请求的参数传递方式和你当前写法不匹配导致的。先给你拆解问题,再给你修正后的代码:

问题分析

  1. GET请求不需要设置contentType:你代码里写的contentType: "appl..."是多余的,因为GET请求没有请求体,这个属性是用来告诉服务器请求体的格式,设置了反而可能干扰参数解析。
  2. 参数没有正确传递:你定义了AppointmentDate变量,但没有把它传递到后端方法里,或者参数名称和后端方法的参数名不匹配,导致后端接收不到值。

前提确认

首先要确保你的后端Controller方法参数名称和前端要传的参数名完全一致(大小写敏感),比如后端方法应该是这样的(两种类型都给你列出来):

// 字符串类型参数
public ActionResult GetTimeSlotsByDate(string AppointmentDate)
{
    // 你的业务逻辑
    return Json(timeSlots, JsonRequestBehavior.AllowGet);
}

// 或者DateTime类型参数
public ActionResult GetTimeSlotsByDate(DateTime AppointmentDate)
{
    // 你的业务逻辑
    return Json(timeSlots, JsonRequestBehavior.AllowGet);
}

修正后的前端代码

给你两种常用的GET请求传参方式,选一种就行:

方式一:直接拼接到URL中

这种方式最直观,jQuery会自动帮你处理编码:

$('#AppointmentDate').change(function () { 
    var AppointmentDate = '2018-04-30'; // 可以换成document.getElementById('AppointmentDate').value;
    // 把参数拼到生成的URL后面
    var requestUrl = '@Url.Action("GetTimeSlotsByDate", "Appointment")' + '?AppointmentDate=' + encodeURIComponent(AppointmentDate);
    
    $.ajax({
        url: requestUrl,
        type: 'GET',
        success: function (response) {
            // 处理返回的时间槽数据
            console.log('返回的时间槽:', response);
        },
        error: function (xhr) {
            console.error('请求出错啦:', xhr);
        }
    });
});

方式二:使用data属性传递

jQuery会自动把data里的键值对转换成URL查询参数,更简洁:

$('#AppointmentDate').change(function () { 
    var AppointmentDate = '2018-04-30'; // 换成document.getElementById('AppointmentDate').value;
    
    $.ajax({
        url: '@Url.Action("GetTimeSlotsByDate", "Appointment")',
        type: 'GET',
        data: { AppointmentDate: AppointmentDate }, // 键名必须和后端参数名完全一致
        success: function (response) {
            console.log('返回的时间槽:', response);
        },
        error: function (xhr) {
            console.error('请求出错啦:', xhr);
        }
    });
});

额外注意点

  • 如果后端参数是DateTime类型,要确保前端传递的日期格式是.NET能识别的,比如'2018-04-30'这种ISO格式就没问题,要是其他格式可能需要在后端用[DisplayFormat(DataFormatString = "yyyy-MM-dd")]标注参数。
  • 一定要保证前后端参数名称完全一致,比如后端是string appointmentDate(小写开头),那前端data里的键名也要写成appointmentDate,不然会匹配失败导致参数为null。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 02:23:34