我的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.numItemQty.unitnull

经过进一步调查,在将JavaScript对象传递给C#控制器之前。对象已成功填充。

我需要ItemQty作为ExpandoObject,因为ItemQty下的字段/属性总是在变化/动态

问题:


(不完整的话题)为什么_model.ItemDesc.value = 'Descript'错误?另一方面,_model.ItemDesc = 'Descript'运行没有错误。
为什么在ItemQty属性中出现空值?

最佳答案

(不完整的话题)为什么_model.ItemDesc.value = 'Descript'错误?另一方面,_model.ItemDesc = 'Descript'运行没有错误。


由于原始javascript ItemDesc中没有属性ItemQtyItemQtyObject

您可以尝试为您的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无法通过ExpandoObjectJSON对象找到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; }
}

关于javascript - Javascript将空值传递给C# Controller 参数中的ExpandoObject字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53295349/

10-09 09:54