【问题标题】:Passing a JSON Array of Objects to Controller using AJAX使用 AJAX 将 JSON 对象数组传递给控制器
【发布时间】:2018-09-25 20:45:53
【问题描述】:

我正在尝试将一个对象数组传递给控制器​​,其中包含表单发布的值。每次当我传递数组时,它都会在控制器的操作中给我 null。

下面是称为 Itemspecs 的对象数组

[object Array]: [Object, Object, Object]

0: Object
ItemID: 0
PropertyID: 7
Value: "hj"
ValueID: 0

1: Object
ItemID: 0
PropertyID: 8
Value: "Red"
ValueID: 0

2: Object
ItemID: 0
PropertyID: 19
Value: "jh"
ValueID: 0

jQuery

jQuery.ajaxSettings.traditional = true
$.ajax({
     type: 'POST',
     cache: false,
     url: '/Item/AddOrEdit',
     contentType: 'application/json; charset=utf-8',
     dataType:'json',
     //data: $(form).serialize()
     data: JSON.stringify({ form, Itemspecs })
});

我在数据中传递了两个参数。参数form 是来自MVC 表单的值,Itempecs1 是我的数组

public ActionResult AddOrEdit(List<ValueViewModel> Itemspecs, ItemViewModel form)
{ 
    // Save posted data
}

我在AddOrEdit 操作中收到表单值,但不是数组。

阵列模型:

public class ValueViewModel
{
    public int ValueID { get; set; }
    [Required(ErrorMessage = "This Field is Required")]
    public string Value { get; set; }
    public int PropertyID { get; set; }
    public int ItemID { get; set; }
}

这就是我如何通过组合其他两个数组来制作这个 itemspecs 数组

var Value = [];
$('#SpecsPlaceHolder :input').each(function () {
    Value.push($(this).val());
});
console.log(Value + ": These Are Values");

var PropertyID = [];

$('#SpecsPlaceHolder :input').each(function (index) {
    // For debugging purposes...
    //alert(index + ': ' + $(this).attr('id'));
    PropertyID.push($(this).data("id"));
    //PropertyID.push($(this).attr('id'));

});
console.log(PropertyID + ": These Are Ids");

var Itemspecs = [];
$.each(PropertyID, function (index, value) {
    Itemspecs.push({ 'ValueID': 0, 'Value': Value[index], 'PropertyID': value, 'ItemID': 0, });
});

Value = (3) ["gh", "Red", "hg"]PropertyID = (3) [7, 8, 19] 然后将它们组合到 itemspecs 中,在控制台中返回如下对象数组:

(3) [{…}, {…}, {…}]
0:{ValueID: 0, Value: "gh", PropertyID: 7, ItemID: 0}
1:{ValueID: 0, Value: "Red", PropertyID: 8, ItemID: 0}
2:{ValueID: 0, Value: "hg", PropertyID: 19, ItemID: 0}
length:3
__proto__:Array(0)

【问题讨论】:

    标签: jquery .net json ajax model-view-controller


    【解决方案1】:

    所以我所做的是在当前 Ajax 的成功中调用另一个 Ajax,并在第一个中发送表单,在第二个中发送数组

    $.ajax({
                    type: 'POST',
                    url: form.action,
                    data: $(form).serialize(),
                    success: function (response) {
    
                        if (response.success && response.data > 0)
                        {
                            debugger
                            var Itemspecs = [];
                        $.each(PropertyID, function (index, value) {
                            Itemspecs.push({ 'ValueID': 0, 'Value': Value[index], 'PropertyID': value, 'ItemID': response.data });
                        });
    
                        console.log(Itemspecs);
    
                        $.ajax({
                            type: 'POST',
                            url: '@Url.Action("PostData", "Item")/',
                            cache: false,
                            contentType: 'application/json; charset=utf-8',
                            dataType: 'json',
                            data: JSON.stringify(Itemspecs),
    
                            success: function (response) {
                                if (response.success) {
                                    Popup.dialog('close');
                                    dataTable.ajax.reload();
                                    $.notify(response.message, {
                                        globalPosition: "top center",
                                        className: "success"
                                    })
                                }
                            }
                        });
                        }
                    }
           });
    

    【讨论】:

      【解决方案2】:

      发布的 JSON 缺少 form 日期,并且您的 JSON 应该有 form 对应 ItemViewModel formItemspecs 对应 ItemViewModel form,模型属性的命名约定相同。

      您的 JSON 应如下所示

      {
        "form": {
          "status": "0001",
          "date": "0002"
        },
        "Itemspecs": [
          {
            "ItemID": 0,
            "PropertyID": 7,
            "Value": "hj",
            "ValueID": 0
          },
          {
            "ItemID": 0,
            "PropertyID": 8,
            "Value": "Red",
            "ValueID": 0
          }
        ]
      }
      

      使用下面的 JS 将填充缺少的 form 数据,以便您可以在控制器中接收它

      // sample data for test
      var Itemspecs =
          [
              { "ItemID": 0, "PropertyID": 7, "Value": "hj", "ValueID": 0 },
              { "ItemID": 0, "PropertyID": 7, "Value": "hj", "ValueID": 0 }
          ]; 
      
      var form = {};
      
      // loop throw form and get all data
      $.each($('#form1').serializeArray(), function (i, field) {
          form[field.name] = field.value || '';
      });
      
      jQuery.ajaxSettings.traditional = true
      $.ajax({
          type: 'POST',
          cache: false,
          url: '/Item/AddOrEdit',
          contentType: 'application/json; charset=utf-8',
          dataType: 'json',
          data: JSON.stringify({ form, Itemspecs })
      });
      

      【讨论】:

        猜你喜欢
        • 2016-01-04
        • 2013-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-01
        • 2017-01-11
        • 1970-01-01
        相关资源
        最近更新 更多