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

如何在dataType为HTML的jQuery Ajax请求中传多参数至ASP.NET Core控制器

解决ASP.NET Core中jQuery Ajax(dataType为HTML)传递参数时控制器接收为null的问题

问题场景

使用以下jQuery Ajax代码调用ASP.NET Core控制器的POST方法,期望传递TFObj对象到后台,但控制器接收的RequestModel始终为null:

jQuery请求代码

$.ajax({
    url: '@Url.Action("GetItemsForRelease", "PointOfSales")',
    data: { requestModel: TFObj },
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    dataType: "html",
    success: function (responsedata) {
        $("#releaseItemsPush").html(responsedata);
    },
    error: function (error) {
        console.log(error);
    }
});

控制器Action代码

[HttpPost]
public ActionResult GetItemsForRelease(RequestModel requestModel)
{
  return PartialView("_partialReleaseItem", requestModel);
}

原因分析

  1. Content-Type与数据格式不匹配:设置了contentType: "application/json",但直接传递JavaScript对象{ requestModel: TFObj },jQuery不会自动将其序列化为JSON字符串,导致请求体格式不符合JSON规范,模型绑定失败。
  2. 缺少模型绑定标识:ASP.NET Core默认从表单数据绑定模型,当使用JSON格式传递参数时,需明确告知框架从请求体读取JSON数据,否则无法正确绑定到RequestModel对象。

解决方案

方案一:JSON格式传参(推荐)

修改jQuery代码将数据序列化为JSON字符串,同时在控制器参数上添加[FromBody]特性:

修改后的jQuery代码

$.ajax({
    url: '@Url.Action("GetItemsForRelease", "PointOfSales")',
    // 将对象序列化为JSON字符串
    data: JSON.stringify(TFObj),
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    dataType: "html",
    success: function (responsedata) {
        $("#releaseItemsPush").html(responsedata);
    },
    error: function (error) {
        console.log(error);
    }
});

修改后的控制器代码

[HttpPost]
// 添加[FromBody]特性,指定从请求体的JSON中绑定模型
public ActionResult GetItemsForRelease([FromBody] RequestModel requestModel)
{
  return PartialView("_partialReleaseItem", requestModel);
}

方案二:表单格式传参

若无需使用JSON格式,可移除contentType设置(默认值为application/x-www-form-urlencoded),直接传递TFObj对象(需确保对象属性名与RequestModel属性名一致):

修改后的jQuery代码

$.ajax({
    url: '@Url.Action("GetItemsForRelease", "PointOfSales")',
    // 直接传递TFObj的属性集合
    data: TFObj,
    type: 'POST',
    dataType: "html",
    success: function (responsedata) {
        $("#releaseItemsPush").html(responsedata);
    },
    error: function (error) {
        console.log(error);
    }
});

控制器代码(无需修改)

[HttpPost]
public ActionResult GetItemsForRelease(RequestModel requestModel)
{
  return PartialView("_partialReleaseItem", requestModel);
}

注意事项

  • 若TFObj是嵌套对象,方案二需手动展开嵌套属性,否则模型绑定无法识别,此时优先选择方案一。
  • dataType: "html"仅指定预期的响应格式,与请求参数的传递格式无关,两种方案均可正常接收HTML响应。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 10:30:58