我的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#CreateItemModel
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对象,它通过一个CreateItemModel
参数传递给我的C#控制器,该参数的字段为ItemQty
作为ExpandoObject
。但是,传递给我的C#控制器之后。 ItemQty.num
和ItemQty.unit
是null
。
在将JavaScript对象传递给C#控制器之前,需要进一步调查。对象已成功填充。
我需要ItemQty
作为ExpandoObject
,因为ItemQty
下的字段/属性总是在变化/动态
问题:
_model.ItemDesc.value = 'Descript'
错误?另一方面,_model.ItemDesc = 'Descript'
正常运行。ItemQty
属性中得到空值?答案 0 :(得分:1)
(有点话题)为什么
_model.ItemDesc.value = 'Descript'
错误?另一方面,_model.ItemDesc = 'Descript'
正常运行。
因为原始javascript ItemDesc
中没有属性ItemQty
,ItemQty
,Object
。
您可以尝试为您的JavaScript代码创建匿名JSON对象。
var _model = {
ItemDesc: {
value : "Descript"
},
ItemQty :{
num : 1,
unit :'pcs'
}
};
代替
var _model = new Object();
_model.ItemDesc.value = 'Descript';
_model.ItemQty.num = 1;
_model.ItemQty.unit = 'pcs'
您的c#模型可能看起来像是因为您当前的ItemDesc
是一个对象而不是字符串值。
为什么我在
nulls
属性中得到ItemQty
?
因为默认的ModelBindiner无法通过您的ExpandoObject
键JSON
对象找到ItemQty
。
public class ItemDesc
{
public string value { get; set; }
}
public class ItemQty
{
public int num { get; set; }
public string unit { get; set; }
}
public class CreateItemModel
{
public ItemDesc ItemDescContext { get; set; }
public ItemQty ItemQtyContext { get; set; }
}