如何读取传入的 Json 字符串并将其从 ajax 映射到 C# asp.ne MVC 控制器

How to read and map an incoming Json String from ajax to C# asp.ne MVC Controller

Ajax:

 $.ajax({
        async: true,
        type: 'Post',
        contentType: 'application/json',
        dataType: 'json',
        traditional: true,
        processData: false,
        data: JSON.stringify(myData),
        url: '/Shopping/Order',
        success: function (response) {
            console.log("response.sussces: " + response.success);
            console.log("response.message: " + response.message);
            console.log("response.data: " + response.data);
        },
        error: function (response) {
            console.log(response);
        }
    });

我正在尝试迭代 ItemList,json 格式为

{
 "ItemList": [
  {
    "id": 3,
    "name": "Item 3",
    "desc": "Lorem Ipsum is simply dummy text",
    "price": 361.05,
    "image": "../images/no_image.png",
    "count": 1
  },
  {
    ...
  },
  ...
 ]
}

我的控制器:

    [HttpPost]
    public JsonResult Order([FromBody] ItemList list)
    {

        var response = new
        {
            Success = true,
            Message = "Item Added Succesfully",
            Data = list.Items.Count() // result: System.ArgumentNullException: value can't be null
        };

        var jsonResult = Json(response);

        return jsonResult;
    }

当我将 list.ToString() 分配给数据时。 数据值变为 ( ShowCase.Controllers.ItemList ).

另一方面,当我将参数声明为对象类型时,我收到来自 ajax 的传入数据。

修改后的控制器:

    [HttpPost]
    public JsonResult Order([FromBody] Object list)
    {


        var response = new
        {
            Success = true,
            Message = "Item Added Succesfully",
            Data = list.ToString()
        };

        var jsonResult = Json(response);

        return jsonResult;
    }

如有任何帮助,我们将不胜感激。

已编辑:物品和物品列表类

    public class Item
    {
      public int Id { get; set; }
      public string Name { get; set; }
      public string Desc { get; set; }
      public double Price { get; set; }
      public string Image { get; set; }
      public int Count { get; set; }
    }

    public class ItemList
    {
      public List<Item> Items { get; set; }
    }

Json 字符串列表:var myData = {ItemList: JSON.parse(sessionStorage.getItem('shoppingCart'))};

制作这个:

“物品清单”:[ { “编号”:3, "name": "项目 3", "desc": "Lorem Ipsum 只是虚拟文本", “价格”:361.05, "图片": "../images/no_image.png", “计数”:1 }, { ... }, ... ] }

ItemList 是您的 JSON 对象的 属性。因此,如下所示创建一个新的 class,它应该具有 ItemList 作为 属性。

public class OrderRequest
{
    public ItemList ItemList {get; set; }
}

并将动作签名更改为

[HttpPost]
public JsonResult Order([FromBody]OrderRequest orderRequest)

并访问计数

Data = orderRequest.ItemList.Items.Count()