AJAX和Web Api Post方法 - 它是如何工作的?

Yec*_*ats 24 c# ajax jquery asp.net-web-api

我正在尝试使用AJAX/Jquery和c#写入我的数据库.每当我将参数传递给C#代码时,它都显示为null.我正在使用visual studio在创建控制器类时生成的默认模板.任何帮助,将不胜感激!

NOte:这是我打算打电话给的休息服务.(一个普通的ASP网站......不是MVC.而且,GET Rest api非常有效.)

jQuery的/ AJAX:

        var dataJSON = { "name": "test" }

        $('#testPostMethod').bind("click", GeneralPost);
        function GeneralPost() {
            $.ajax({
                type: 'POST',
                url: '../api/NewRecipe',
                data:JSON.stringify(dataJSON),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json'
            });
        }
Run Code Online (Sandbox Code Playgroud)

C#

    //If I remove the [FromBody] Tag then when I click the button this method is never called.
    public void Post([FromBody]string name)

    {

    }
Run Code Online (Sandbox Code Playgroud)

编辑:

我稍微调整了我的代码,但仍遇到同样的问题.回顾一下,它正在加载POST方法,但它传入的是null.

C#

 public class RecipeInformation
    {
        public string name { get; set; }

    }

        public void Post(RecipeInformation information)

        {

        }
Run Code Online (Sandbox Code Playgroud)

AJAX:

    var dataJSON = { information: { name: "test" } };

    $('#testPostMethod').bind("click", GeneralPost);
    console.log(dataJSON);
    function GeneralPost() {
        $.ajax({
            type: 'POST',
            url: '../api/NewRecipe',
            data: dataJSON,
            contentType: 'application/json; charset=utf-8',
        });
    }
Run Code Online (Sandbox Code Playgroud)

cuo*_*gle 51

对于简单类型,在服务器端:

public void Post([FromBody]string name)
{
}
Run Code Online (Sandbox Code Playgroud)

在客户端,您只需定义是否要以json格式发送:

    var dataJSON = "test";

    $('#testPostMethod').bind("click", GeneralPost);
    function GeneralPost() {
        $.ajax({
            type: 'POST',
            url: '/api/NewRecipe',
            data: JSON.stringify(dataJSON),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json'
        });
    }
Run Code Online (Sandbox Code Playgroud)

如果你想让它在复杂类型中工作,从服务器端你应该定义:

public class RecipeInformation
{
    public string name { get; set; }
}

public class ValuesController : ApiController
{
    public void Post(RecipeInformation information)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

从客户端:

    var dataJSON = { name: "test" };

    $('#testPostMethod').bind("click", GeneralPost);
    function GeneralPost() {
        $.ajax({
            type: 'POST',
            url: '/api/NewRecipe',
            data: JSON.stringify(dataJSON),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json'
        });
    }
Run Code Online (Sandbox Code Playgroud)