我的 Javascript 代码
$('[step="4"]').click(function () {
//shortened for brevety
var _model = new Object();
_model.ItemDesc.value = 'Descript';
//^ throws an error but gets fixed if removing the .value
_model.ItemQty.num = 1;
_model.ItemQty.unit = 'pcs'
$.ajax({
type: "POST",
url: 'CreateItemCallAsync',
data: _model,
success: function (msg) {
status = JSON.stringify(msg);
alert('Item created successfully!');
location.reload();
},
error: function (msg) {
status = JSON.stringify(msg);
alert('Failed to create item.');
location.reload();
}
});
});
C# 控制器代码
[HttpPost]
public async Task<JsonResult> CreateItemCallAsync(CreateItemModel item)
{
//breakpoint here
var test = item.ItemDesc;
var qty = item.ItemQty.num; //getting nulls here
var unit = item.ItemQty.unit; //getting nulls here
}
C# 创建项目模型
public class CreateItemModel
{
public string ItemName { get; set; }
public string ItemDesc { get; set; }
public ExpandoObject ItemQty { get; set; }
}
JavaScript 对象
[
{
ItemName : 'Item1',
ItemDesc : 'Descript'
ItemQty : { num : 5 , unit: 'pcs'}
},
{
ItemName : 'Item2',
ItemDesc : 'Descript'
ItemQty : { num : 1 , unit: 'box'}
}
]
从上面的代码。我有一个 JavaScript 对象传递给我的 C# 控制器,其CreateItemModel
参数的字段ItemQty
为ExpandoObject
. 但是,在传递给我的 C# 控制器之后。ItemQty.num
和ItemQty.unit
是null
。_
通过进一步调查,在将 JavaScript 对象传递给 C# 控制器之前。对象已成功填充。
我需要ItemQty
一个,ExpandoObject
因为下面的字段/属性ItemQty
总是在变化/动态
问题:
- (题外话)为什么会
_model.ItemDesc.value = 'Descript'
出错?另一方面_model.ItemDesc = 'Descript'
运行没有错误。 - 为什么我在
ItemQty
属性中得到空值?