将多维数组从ajax传递给action

时间:2015-02-26 17:02:06

标签: jquery asp.net-mvc-4

我无法从AJAX调用中获取数据到我的操作。以下是我在javascript方面构建数组的方法:

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

然后我打电话给我:

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

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

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

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

但是,您不应该将字典传递给GET方法。除了您创建的丑陋查询字符串之外,您可以轻松地超出查询字符串字符限制并抛出异常。而是发布数据。

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