【问题标题】:Sending a jQuery array back to a c# String Array将 jQuery 数组发送回 c# 字符串数组
【发布时间】:2015-01-20 15:51:29
【问题描述】:

我有一个需要 String[] 数组的 C# 方法,我使用 $.getJSON 调用将参数传递给控制器​​中的方法。

我正在获取已选择的复选框的值并将它们传递回控制器,但是当我使用 Stringify 时,它会将多个值放在一起,并且当我将数组传递其自身时,会有多个条目,但是接收String[] 为空。

var array = new Array();
$('#ids:checked').each(function() {
    array.push($(this).val())
}

var jsonText = JSON.stringify(array); // I have tried this, but to receive one entry
var dataValues = { 
    ids: jsonText, 
    id: $('#idNumber').val(), 
    orderId: $('#orderId').val()
};

$.getJSON("/path/to/method", dataValues, function(){});
public ActionResult doSomething(String[] ids, Int32 Id, Int32 OrderId)
{
    //do something here
}

感谢您的帮助。

【问题讨论】:

  • 您的 orderId 属性中有错字 - 括号位置错误,引号不匹配。
  • 修正了,不是复制/粘贴,我重新输入了。
  • 应该是JSON.stringify 而不是JSON.Stringify

标签: c# jquery arrays model-view-controller


【解决方案1】:

您正在将 ids 的值设置为 JSON 字符串;但是,服务器无法知道这一点。据服务器所知,ids 是一个string 值,无法转换为string[]

您应该将整个数据对象转换为 JSON 并指定其内容类型,而不是将一个值转换为 JSON:

var dataValues = { 
    ids: array, //the Javascript array, *not* the JSON string
    id: $('#idNumber').val(), 
    orderId: $('#orderId').val()
};

$.ajax({
    url: "/path/to/method", 
    data: JSON.stringify(dataValues),
    success: function(){},
    contentType: "application/json"
});

【讨论】:

  • 这就像一种享受,也感谢您的解释。
【解决方案2】:

我之前没有使用 GET 回传数组,我通常使用 POST,类似这样:

var sData = JSON.stringify({ ids: array});

        $.ajax({
            url: "/path/to/method",
            data: sData,
            method: 'POST',
            contentType: "application/json; charset=utf-8",
            success: function (result) {


            },
            error: function (result) {
            }
    });

你的情况可能是:

    var dataValues = JSON.Stringify({ 
        ids: array, 
        id: $('#idNumber').val(), 
        orderId: $('#orderId').val()
    });

$.ajax({
                url: "/path/to/method",
                data: sData,
                method: 'GET',
                contentType: "application/json; charset=utf-8",
                success: function (result) {


                },
                error: function (result) {
                }
        });

   // $.getJSON("/path/to/method", dataValues, function(){});

【讨论】:

    猜你喜欢
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    相关资源
    最近更新 更多