使用AJAX将JSON对象数组传递给Controller

时间:2018-04-16 07:30:09

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

我正在尝试将一个对象数组传递给控制器​​,并使用表单发布的值。每次当我传递数组时,它都会在Controller的动作中给我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中,这些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)

2 个答案:

答案 0 :(得分:0)

所以我做的是在当前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"
                                })
                            }
                        }
                    });
                    }
                }
       });

答案 1 :(得分:0)

发布的JSON缺少form日期,您的JSON应该form ItemViewModel form Itemspecs ItemViewModel form { "form": { "status": "0001", "date": "0002" }, "Itemspecs": [ { "ItemID": 0, "PropertyID": 7, "Value": "hj", "ValueID": 0 }, { "ItemID": 0, "PropertyID": 8, "Value": "Red", "ValueID": 0 } ] } 具有相同的模型属性命名约定。< / p>

您的JSON应如下所示

form

使用下面的JS将填充缺失的// 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 }) }); 数据,以便您可以在控制器中接收它

{{1}}