将 ajax 中的多维数组传递给操作

Pass multidimensional array from ajax to action

我无法从对我的操作的 AJAX 调用中获取数据。以下是我如何在事物的 javascript 端构建数组:

$("input[type=checkbox]").each(function (index){
    if ($(this).attr('id').indexOf("UniqueID_") > -1) {
        savedParams.uniqueIds.push([$(this).attr('id'), $(this).is(":checked")]);
    }
});

然后我 ajax 打电话:

return $.get('<%= Url.Action("GridData") %>', savedParams).done(
    function(rows, status, xhr) {
        doSomething();
    });

当我到达终点时,字典中填充了正确数量的条目,但值都是错误的。这是我的终点:

public ActionResult GridData(Dictionary<string,bool> uniqueIds = null)

在 Fiddler 中捕获请求显示格式似乎是正确的:

GET /Transactions/GridData?2%5B0%5D%5B%5D=UniqueID_1&uniqueIds%5B0%5D%5B%5D=true&uniqueIds%5B1%5D%5B%5D=UniqueID_2&uniqueIds%5B1%5D%5B%5D=true&uniqueIds%5B2%5D%5B%5D=UniqueID_3&uniqueIds%5B2%5D%5B%5D=true HTTP/1.1

感谢任何帮助!

为了将字典传回该方法,您的 javascript 对象需要采用以下格式

var savedParams = { 'uniqueIds[0].key': 'ABC', 'uniqueIds[0].value': 'True', 'uniqueIds[1].key': 'DEF', 'uniqueIds[1].value': 'True', .... };

但是,您不应将字典传递给 GET 方法。除了您创建的难看的查询字符串之外,您还可以轻松地超出查询字符串字符限制并引发异常。取而代之的是 post 数据。

在任何情况下,您都可以通过使用视图模型(例如使用属性 string IDbool IsSelected 并在 [=13= 中使用 HtmlHelpers 正确构建 html 来避免所有这些] 循环,这样你就可以 post 回到 public ActionResult GridData(IEnumerable<MyViewModel> model)。然后就是 savedParams = $('form').serialize();