【问题标题】:Passing object from jquery ajax to WebAPI results to null将对象从 jquery ajax 传递到 WebAPI 结果为 null
【发布时间】:2014-12-20 01:19:19
【问题描述】:

在 HTML 上:

<div>
    <button onclick="clicker()">Click Me!</button>
</div>

<script type="text/javascript">
    function clicker() {
        var data = {
          id: 1,
          name: 'julius'
        };

        $.ajax({
            type: 'POST',
            url: '/api/test/',
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8"
        });
    }
</script>

在控制器上:

public class TestController : ApiController
{
    public void Post([FromBody]string value)
    {
      Console.WriteLine();
    }
}

控制器上的变量“value”的值为空,不过,我将数据传递给 ajax 调用。有人能解释一下为什么会这样吗?

【问题讨论】:

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


    【解决方案1】:

    与其尝试将发布的内容作为字符串接收,不如创建一个对象来封装您发布的属性:

    public class Data
    {
        public int id { get; set; }
        public string name { get; set; }
    }
    

    然后将您的控制器更改为:

    public class TestController : ApiController
    {
        public void Post(Data value)
        {
          int id = value.id;
          string name = value.name;
        }
    }
    

    如果您真的想以字符串形式接收发布的数据,Darrel Miller 的这篇博文可能会有所帮助:

    Posting raw JSON to Web API.

    【讨论】:

    • 感谢 Jon 分享想法和博文! =)
    猜你喜欢
    • 1970-01-01
    • 2013-03-26
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    相关资源
    最近更新 更多