【问题标题】:Sending JSON from View to Controller ASP.NET MVC gives null values将 JSON 从视图发送到控制器 ASP.NET MVC 会给出空值
【发布时间】:2021-09-23 03:23:06
【问题描述】:

我在将 JSON 数据从 MVC 视图发送到控制器时遇到问题,我得到的只是控制器:

我在 Url.Action 中发送的 JSON 如下所示:(我自己通过 .push() 将数组添加到数组,然后通过 JSON.stringify 创建它)

[
   [
      {
         "isOrdered":false,
         "orderLineId":"4550",
         "comment":"",
         "orderId":"2789"
      }
   ],
   [
      {
         "isOrdered":false,
         "orderLineId":"4551",
         "comment":"",
         "orderId":"2789"
      }
   ]
]

我使用 JQuery ajax POST

$.ajax({
            type: "POST",
            url: "@Url.Action("SaveCheckboxesAndComments")",
            data: JSON.stringify(array),
            traditional: true,
            contentType: "application/json; charset=utf-8",
            dataType: 'json'
        });

和我的控制器:

public class JsonData
        {
            public bool IsOrdered { get; set; }
            public string OrderLineId { get; set; }
            public string Comment { get; set; }
            public int OrderId { get; set; }
        }

        [HttpPost]
        public async Task<ActionResult> SaveCheckboxesAndComments(List<JsonData> jsonArray)
        {...

我应该更改我的类 JsonData 或 JS 中的某些内容以获取值吗?因为不知何故“框架”在起作用。

【问题讨论】:

    标签: javascript jquery json asp.net-mvc model-view-controller


    【解决方案1】:

    一些尝试:

    1. 在开发控制台中打开“网络”选项卡,查看 POST 请求的详细信息,以确保 URL 正确且发送的 JSON 符合您的预期
    2. 使用[DataContract] 属性装饰JsonData 类,并使用[DataMember(Name = "Name")] 属性装饰每个属性 - 以确保您不会遇到大小写问题(类中的属性名称全部大写,并且您的 json 以每个小写字母开头)。
    3. 看起来您在生成的 Json 上有一组额外的外部 [ ] 括号。因此,虽然您的操作期待 List&lt;JsonData&gt; jsonArray,但它正在发送 List&lt;List&lt;JsonData&gt; jsonArray&gt;。看看它是如何从正在发送的 json 中删除最外面的方括号的。

    【讨论】:

    • 到底是什么问题?
    • 我使用了您的 2. 和 3. 选项,但我发送的对象有误,这完全是关于额外的 [ ]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    • 2014-06-29
    • 1970-01-01
    • 2012-05-16
    • 2021-04-09
    • 1970-01-01
    相关资源
    最近更新 更多