1

我的 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参数的字段ItemQtyExpandoObject. 但是,在传递给我的 C# 控制器之后。ItemQty.numItemQty.unitnull。_

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

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

问题:

  1. (题外话)为什么会_model.ItemDesc.value = 'Descript'出错?另一方面_model.ItemDesc = 'Descript'运行没有错误。
  2. 为什么我在ItemQty属性中得到空值?
4

1 回答 1

1

(题外话)为什么会_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 无法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; }
}
于 2018-11-14T08:01:57.393 回答