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

如何将jQuery键值对传入C#控制器Action的Dictionary中

如何将JavaScript键值对正确传入C#控制器Action?

嘿,我来帮你搞定这个传参问题!你已经用JavaScript正确构建了存储ItemID和价格的键值对product_ids,但直接用$.post传对象的话,C#控制器那边可能没法正确解析,这里有两个实用方案:

方案1:序列化JSON字符串后传递,后端反序列化

这种方式兼容性好,适合大多数场景。首先修改前端的请求代码,把product_ids序列化为JSON字符串:

var product_ids = {};
$(document).on('click', '.chkItem', function () {
    if ($(this).is(':checked')) {
        product_ids[$(this).attr('id')] = $(this).attr("price");
    } else {
        delete product_ids[$(this).attr('id')];
    }
});

// 传参时将对象转为JSON字符串
$.post("/Controller/GetAllProducts", { ids: JSON.stringify(product_ids) })
.done(function(response) {
    // 处理成功响应
})
.fail(function(xhr) {
    // 处理请求错误
});

然后在C#控制器的Action里,先接收字符串,再反序列化为字典:

// 如果你用的是.NET Framework,可引用Newtonsoft.Json(NuGet安装)
using Newtonsoft.Json;
// .NET Core 3.0+ 可用System.Text.Json替代

public ActionResult GetAllProducts(string ids)
{
    // 反序列化为Dictionary,键是ItemID,值是价格
    var productDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(ids);
    
    // 这里就可以直接使用productDict处理业务逻辑了
    foreach (var item in productDict)
    {
        string itemId = item.Key;
        string price = item.Value;
        // 你的业务代码...
    }
    
    return Json(new { Success = true });
}

方案2:直接发送JSON请求,后端接收Dictionary类型

这种方式更简洁,需要确保前端发送的是JSON格式的请求,而不是默认的表单编码:

var product_ids = {};
$(document).on('click', '.chkItem', function () {
    if ($(this).is(':checked')) {
        product_ids[$(this).attr('id')] = $(this).attr("price");
    } else {
        delete product_ids[$(this).attr('id')];
    }
});

// 使用$.ajax指定请求内容类型为JSON
$.ajax({
    url: "/Controller/GetAllProducts",
    type: "POST",
    contentType: "application/json; charset=utf-8", // 关键:告诉后端是JSON数据
    data: JSON.stringify(product_ids), // 直接序列化整个键值对对象
    success: function(response) {
        // 处理成功响应
    },
    error: function(xhr) {
        // 处理请求错误
    }
});

后端的Action可以直接接收Dictionary类型(注意键值类型要和前端匹配,前端价格是字符串,所以用string;如果是数字可改成decimal):

public ActionResult GetAllProducts(Dictionary<string, string> product_ids)
{
    // 直接使用传入的product_ids字典
    foreach (var item in product_ids)
    {
        string itemId = item.Key;
        string price = item.Value;
        // 你的业务代码...
    }
    
    return Json(new { Success = true });
}

几个关键注意点

  • 类型匹配:前端传入的价格如果是字符串,后端就用string接收;如果是数字(比如parseFloat($(this).attr("price"))),后端可以用decimal或double,避免类型转换错误。
  • 路由正确性:确保请求URL中的控制器名称是实际的控制器类名(比如控制器是ProductController,URL应该是/Product/GetAllProducts)。
  • .NET Core兼容:如果是.NET Core项目,默认使用System.Text.Json,反序列化时替换为System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, string>>(ids)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:52:47