如何附加已选中/未选中的复选框值以发布数据

时间:2018-07-11 20:48:05

标签: javascript c# jquery arrays asp.net-mvc

在JavaScript(可以使用jQuery)中,我该如何打开对象数组形式的内容:

// Array of objects.
var myArray = [ { code: "X", selected: true }, { code: "Y", selected: false }, { code: "Z", selected: true } ];

到二维值数组中?:

var myArray[0][0] = "X";
myArray[0][1] = true;
myArray[1][0] = "Y";
myArray[1][1] = false;
myArray[2][0] = "Z";
myArray[2][1] = true;

我问是因为我在将序列化表格数据与对象数组结合在一起的AJAX调用中发送数据时遇到麻烦。

我需要所有数据以映射到View Model服务器端:

public class MyViewModel
{
    public MyViewModel()
    {
        selectedRelatedTaxes = new List<RelatedTax>();
    }

    public string co { get; set; }
    public string category { get; set; }
    public string taxCode { get; set; }
    public List<RelatedTax> myArray { get; set; }
}

public class RelatedTax
{
    public string code { get; set; }
    public bool selected { get; set; }
}

这是JavaScript函数,试图将所有数据整理在一起:

function GetAllData() {
    var result = {};

    if (!$('#FormID'))
        return {};

    result = $('#FormID:not(input[data-function="partOfArray"])').serializeArray();

    var myArray = [];
    $('input[data-function="partOfArray"]').each(function (index) {
        var code = $(this).val();
        var selected = $(this).is(':checked');

        myArray.push({ code: code, selected: selected });
    });

    if (result) {
        result.push({ name: 'myArray', value: myArray });
    }

    return result;
}

如果使用上面的函数,我会在AJAX调用中获得该数据:

All of the data necessary for the call. This will not map properly to the list server-side.

该数组未正确映射到列表服务器端。

如果我改用此JavaScript函数:

function Test() {
    var myArray = [];
    $('input[data-function="partOfArray"]').each(function (index) {
        var code = $(this).val();
        var selected = $(this).is(':checked');

        myArray.push({ code: code, selected: selected });
    });

    return { myArray: myArray };
}

对于AJAX调用中的数据,我可以这样做:

Only the array being sent in the AJAX call. This will map properly to the list server-side.

该数组确实正确映射到列表服务器端。但这当然缺少所有其他数据。

第二张图片中的数据格式是什么?对我来说,它看起来像一个二维数组。如何将数据数组与所有其他数据一起转换为该格式?

以下是进行AJAX调用的代码:

function LoadAddCompanyTaxWizard(url) {
    var formData = GetAllData();

    $.ajax(
        {
            cache: false,
            method: "POST",
            url: url,
            data: formData
        },
        .error(...)
        .success(...),
        .complete(...)
    );
}

6 个答案:

答案 0 :(得分:2)

map个数组:

var myArray = [ { code: "X", selected: true }, { code: "Y", selected: false }, { code: "Z", selected: true } ];

var result = myArray.map(({code, selected}) => ([code, selected]));
console.log(result);

答案 1 :(得分:2)

我认为您需要对代码进行如下修改:

function GetAllData() {
  // check if an element exists
  if ($('#FormID').length === 0) {
    return {};
  }

  // use the :not filter correctly
  var result = $('#FormID input:not([data-function="partOfArray"])').serializeArray();

  $('#FormID input[data-function="partOfArray"]').each(function(index) {
    var code = $(this).val();
    var selected = $(this).is(':checked');
    result.push({
      name: "selectedRelatedTaxes[" + index + "][code]",
      value: code
    });
    result.push({
      name: "selectedRelatedTaxes[" + index + "][selected]",
      value: selected
    });
  });

  return result;
}

这是我尝试复制的表格:

function GetAllData() {
  // check if an element exists
  if ($('#FormID').length === 0) {
    return {};
  }

  // use the :not filter correctly
  var result = $('#FormID input:not([data-function="partOfArray"])').serializeArray();

  $('#FormID input[data-function="partOfArray"]').each(function(index) {
    var code = $(this).val();
    var selected = $(this).is(':checked');
    result.push({
      name: "selectedRelatedTaxes[" + index + "][code]",
      value: code
    });
    result.push({
      name: "selectedRelatedTaxes[" + index + "][selected]",
      value: selected
    });
  });

  return result;
}

$("#FormID").on("submit", function(e) {
  e.preventDefault();
  console.log(GetAllData());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<form id="FormID">
  <input name="category" value="State">
  <input name="co" value="CT0002">
  <input name="taxCode" value="AK">
  <input name="selectedRelatedTaxes" data-function="partOfArray" type="checkbox" value="AKSUI" checked="">
  <input name="selectedRelatedTaxes" data-function="partOfArray" type="checkbox" value="AKSUI-E">
  <input name="selectedRelatedTaxes" data-function="partOfArray" type="checkbox" value="FOO" checked="">
  <input name="selectedRelatedTaxes" data-function="partOfArray" type="checkbox" value="BAR">
  <input type="submit" value="Test Script">
</form>

答案 2 :(得分:1)

您可以非常简单地使用.map()Object.values()来做到这一点,就像这样:

var myArray = [ { code: "X", selected: true }, { code: "Y", selected: false }, { code: "Z", selected: true } ];

console.log(myArray.map(obj => Object.values(obj)))

如果您需要保证数组中项目的顺序,可以执行以下操作:

var myArray = [ { code: "X", selected: true }, { code: "Y", selected: false }, { code: "Z", selected: true } ];

console.log(myArray.map(({code, selected}) => [code, selected]))

第二种方法的缺点是它不是动态的,因此您必须显式地对数组中所需的每个元素进行排序。但是从一致的输出来看,这要安全得多。

由于您未在问题中使用ES6,因此非ES6版本将如下所示:

myArray.map(function (obj) {
  return [obj.code, obj.selected]
});

答案 3 :(得分:0)

我会使用reduce两次。

  1. 减少主数组。
  2. 使用键减少对象
  3. 将减少的对象值推入当前数组

var myArray = [ { code: "X", selected: true }, { code: "Y", selected: false }, { code: "Z", selected: true } ];

let result = myArray.reduce((arr, itm, idx) => {
  arr.push(Object.values(itm).reduce((a, i) => a.concat(i), []))
  return arr
}, [])

console.log(result[0][0])
console.log(result[0][1])
console.log(result[1][0])
console.log(result[1][1])
console.log(result[2][0])
console.log(result[2][1])

答案 4 :(得分:0)

这是在JS中创建2d数组的方法

var myArray = [];
    $('input[data-function="partOfArray"]').each(function (index) {
    var code = $(this).val();
    var selected = $(this).is(':checked');
    myArray.push([code, selected]);
});

这将创建您描述的数组:

var myArray[0][0] = "X";
myArray[0][1] = true;
myArray[1][0] = "Y";
myArray[1][1] = false;
myArray[2][0] = "Z";
myArray[2][1] = true;

答案 5 :(得分:0)

ES6中的解决方案,您可以在这里找到很多。

ES5中的解决方案

var myArray =
[
    {code: "X", selected: true},
    {code: "Y", selected: false},
    {code: "Z", selected: true }
];

var newArray = myArray.map(function(obj){return [obj.code, obj.selected]});

console.log(JSON.stringify(newArray, null, '\t'));