将对象从jquery ajax传递到WebAPI的结果为null [英] Passing object from jquery ajax to WebAPI results to null

查看:74
本文介绍了将对象从jquery ajax传递到WebAPI的结果为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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();
    }
}

尽管我将数据传递给ajax调用,但控制器上的变量"value"的值为null.有人可以解释为什么会这样吗?

The value of the variable "value" on the controller is null, although, I pass data to ajax call. Can somebody please explain why this happens?

推荐答案

创建一个对象来封装要发布的属性,而不是尝试以字符串形式接收发布的内容:

Instead of trying to receive the posted content as a string, create an object that encapsulates the properties you are posting:

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

,然后将控制器更改为:

and then change your controller to:

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

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

If you really want to receive the posted data as a string this blog post by Darrel Miller might help:

将原始JSON发布到Web API .

这篇关于将对象从jquery ajax传递到WebAPI的结果为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆