【发布时间】: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