【问题标题】:Pass data to server via POST通过 POST 将数据传递给服务器
【发布时间】:2016-09-28 12:36:19
【问题描述】:

我正在尝试使用 Angular 1.x 在按钮单击时发送数据。

这是来自客户端的调试,对象似乎设置正确:

这是来自服务器端的调试,值丢失了:

还有我的 POCO:

[Serializable]
public class Item
{
    public int Id { get; set; }
    public string Key { get; set; }
    public int Value { get; set; }
    public string Description { get; set; }
}

更新:

这可行,但相当丑陋......

我可以摆脱转换并使用Item类型作为参数,而不是JObject吗?

【问题讨论】:

    标签: javascript c# angularjs ajax asp.net-web-api


    【解决方案1】:

    您想使用 JSON.stringfy() 将 JavScript 值转换为 JSON 字符串。

    $httpost.post("...", JSON.stringify($scope.newItem))
    

    【讨论】:

    • 谢谢,但它不起作用。我试过:i.imgur.com/XRazeah.png 但在服务器端仍然得到 null 和 0s
    • 您是否尝试过使用 Mostafa 的回答中的 JSON.stringify 和 [FromBody]?
    • 你能把参数类型从Item改为object,看看有没有数据发布了吗?
    • 用 stringify 和 FromBody 都试过了,结果还是一样...我想保留我的类型而不是使用对象,但我可能会尝试使用动态...
    • 这就是我所做的(参见有问题的更新),但我不喜欢它......应该是透明的:\
    【解决方案2】:

    使用[FromBody]

    public Add([FromBody] Item item) { ... }
    

    对于复杂类型,Web API 尝试使用媒体类型格式化程序从消息正文中读取值。这包括 [FromBody]、[FromUri] 和 [ModelBinder] 或自定义属性。

    【讨论】:

    • 也试过这个(没有 JSON 字符串化),仍然得到同样的错误结果
    【解决方案3】:

    在你的类声明中添加访问修饰符public

    public class Item
    {
        public int Id { get; set; }
        public string Description { get; set; }
        public int Key { get; set; }
        public string Value { get; set; }
    }
    

    【讨论】:

    • 我的 POCO 已经完全公开,只是将其添加到我的问题中。谢谢
    • 我注意到您在Key 属性中发送的是字符串而不是整数。对吗?
    • 键是字符串是的,请参阅我的 POCO 定义问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    • 2023-01-18
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    相关资源
    最近更新 更多