【问题标题】:Posting json string to c# mvc method将json字符串发布到c#mvc方法
【发布时间】:2020-01-05 23:36:04
【问题描述】:

我有一个 json 字符串(javascript 数组的 json 表示),我想将它传递给 C# 控制器方法。但是,我看到 c# 方法参数为 null 或断点未命中。

这里是js代码:

        $.ajax({
            url: "/Home/PersistSelections",
            type: 'post',
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data:  { "json": JSON.stringify(selectedItems) }

        })

“seleteditems”只是一个 javascript 集合。

我的 c# 代码是:

    [HttpPost]
    public void PersistSelections([FromBody] string json)
    {

    }

但是,这可能不是正确的做法吗?我总是看到 json 参数为空。

感谢任何提示!

【问题讨论】:

    标签: json asp.net-mvc asp.net-core


    【解决方案1】:

    更好的方法是利用模型绑定,而不是尝试自己发布和解析 JSON。

    创建要发送的项目的模型

    public class ItemModel {
        //...include the desired properties
    
        public string Description { get; set; }
        public string Name { get; set; }
        public decimal TotalPrice { get; set; }
    
        //...
    }
    

    下一步更新动作以期望项目

    [HttpPost]
    public IActionResult PersistSelections([FromBody] ItemModel[] items) {
        //access posted items
    }
    

    最后更新客户端以发布 json 数据

    $.ajax({
        url: "/Home/PersistSelections",
        type: 'post',
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data:  JSON.stringify(selectedItems)
    })
    

    框架的内置模型绑定器应该解析和绑定发布的 JSON 并填充控制器中的对象

    【讨论】:

      【解决方案2】:

      由于您使用 contentType 作为 application/json 这就是默认模型绑定器不起作用的原因。如果你想解决这个问题,请创建一个类让我们说模型

        Public Class MyModel{
          Public string Json {get;set;}
         }
      

      在控制器中使用

      [HttpPost]
          public void PersistSelections(MyModel model)
          {
      
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-09
        • 1970-01-01
        • 2016-12-24
        • 1970-01-01
        • 1970-01-01
        • 2016-08-02
        • 2015-10-07
        • 1970-01-01
        相关资源
        最近更新 更多