【问题标题】:How to Post JSON from AngularJS to C# controller如何将 JSON 从 AngularJS 发布到 C# 控制器
【发布时间】:2017-10-03 19:58:37
【问题描述】:

我正在尝试将一个简单的 JSON 发布到 C# 控制器,但我得到了空值。我是 AngularJS 的新手。

这是发布的 angularjs 代码

k = "{ 'id': 1,'name': 'A green door','price': 12.50}";

$http.post("/Inventory/PostSO", k)
    .then(function (response) {
        $scope.message = response.status;
    },
    function (error, status) {
        $scope.message = error.error;
    });

这是 C# 代码,但字符串数据始终为空

public ContentResult PostSO(string data)
{
    return null;
}

我做错了什么?谢谢

【问题讨论】:

  • 为什么要将对象作为字符串发送?
  • 你的问题解决了吗?

标签: javascript c# angularjs json


【解决方案1】:

首先设置请求标头。

内容类型 - 应用程序/json

第二个控制器动作参数是字符串,它必须是一个模型,因为动作描述符试图将发送的模型映射到 C# 对象,创建一个简单的类,并在你的 json 示例中定义所有属性,如数据。

再试一次:)

【讨论】:

    【解决方案2】:

    将 FromBody-Attribute 添加到 Action-Parameter:

    public ContentResult PostSO([FromBody]string data)
    {
        return null;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-22
      • 1970-01-01
      • 1970-01-01
      • 2016-05-28
      相关资源
      最近更新 更多