将键值对jquery数组传递给.NET MVC操作

时间:2016-10-16 20:36:15

标签: javascript jquery arrays asp.net-mvc

我有一个jquery键值对数组如下:

  • 检查复选框时填充数组
  • 如果未选中复选框,则会从中删除该项

该部分的代码是:

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

这很好用,让我们进入下一部分。现在,我正在尝试将所有这些ID从我的视图发送到控制器“Analyze”和操作“Index”,如下所示:

  $(".btnAnalyze").click(function () {
            if (jQuery.isEmptyObject(product_ids) == true) {
                alert("Array is empty");
            }
            else {

                var postData = { values: product_ids };

                $.ajax({
                    type: "POST",
                    url: "/Analyze/Index",
                    data: postData,
                    success: function (data) {
                        alert(data.Result);
                    },
                    dataType: "json",
                    traditional: true
                });

            }
        });

我的行动如下:

 public ActionResult Index(List<string> values)
        {
            string id2= "";
            foreach (var id in values)
            {
                id2= id;
            }
// I'm trying to fetch the ID values here that I added into the array, but I'm not sure how... 

}

使用此当前方法,List值的内容为

"[object Object]" 

这不是我想要的..当我将它们发送到动作索引时,我需要将所有ID很好地整理到列表中......

有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

您正在使用一个对象,而不是一个数组,因此它说它是一个对象。你有两个选择:

  1. 使用实际数组:

    var product_ids = [];
    $(document).on('click', '.chkItem', function () {
      if ($(this).is(':checked')) {
        product_ids.push($(this).attr('id'));
      } else {
        product_ids.splice(product_ids.indexOf($(this).attr('id')), 1);
      }
    });
    
  2. 继续使用对象并使用Object.keys获取属性名称(代码中的ID):

    var postData = { values: Object.keys(product_ids) };
    
  3. 就个人而言,我喜欢#1,因为它更明确地表示您正在捕获已选中复选框的ID,并且对象的属性值始终为"Checked"比任何有意义的东西,但是,嘿,JavaScripts&#39;像那样灵活:)。

答案 1 :(得分:0)

使用console.log(data.Result)调试代替alert(data.Result),因为alert(data.Result) 将您的变量字符串化为[object Object]。要打开控制台,请按F12

相关问题