AJAX & Web Api Post Method - How does it work?

后端 未结 7 672
臣服心动
臣服心动 2020-12-13 14:24

I am trying to write to my database using AJAX / Jquery and c#. Whenever I pass the parameter in to the C# code it shows as null. I am using the default template that visual

7条回答
  •  长情又很酷
    2020-12-13 15:09

    For simple type, on server side:

    public void Post([FromBody]string name)
    {
    }
    

    on the client side, you just define if you want to send in json format:

        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'
            });
        }
    

    If you want to make it work in complex type, from server side you should define:

    public class RecipeInformation
    {
        public string name { get; set; }
    }
    
    public class ValuesController : ApiController
    {
        public void Post(RecipeInformation information)
        {
        }
    }
    

    And from client side:

        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'
            });
        }
    

提交回复
热议问题