C# AJAX 和 Web Api 发布方法 - 它是如何工作的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15687903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:35:52  来源:igfitidea点击:

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

c#jqueryajaxasp.net-web-api

提问by Yecats

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 studio generates when creating a controller class. Any help would be appreciated!

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

NOte: This is a rest service that I am trying to call. (A regular ASP website... not MVC. Also, the GET Rest api works perfectly.)

注意:这是我正在尝试调用的休息服务。(一个普通的 ASP 网站……不是 MVC。另外,GET Rest api 工作得很好。)

Jquery/AJAX:

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

C#

C#

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

    {

    }

EDIT:

编辑:

I have adjusted my code slightly but am still encountering the same issue. To recap, It is loading the POST method, but it is passing in null.

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

C#

C#

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

    }

        public void Post(RecipeInformation information)

        {

        }

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

采纳答案by cuongle

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:

在客户端,您只需定义是否要以 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'
        });
    }

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

回答by S?awomir Rosiek

I suppose that you are using ASP.NET WebAPI and it bind all simple types (int, bool, string, etc) from URL and all complex types from body. When you marked name with FromBodyattribute then it bind it from request body instead of url mapping.

我想您正在使用 ASP.NET WebAPI,它绑定来自 URL 的所有简单类型(int、bool、string 等)和来自正文的所有复杂类型。当您用FromBody属性标记名称时,它会从请求正文而不是 url 映射中绑定它。

You can read more about ASP.NET WebAPI routing and parameter binding here:

您可以在此处阅读有关 ASP.NET WebAPI 路由和参数绑定的更多信息:

回答by Christopher Stevenson

There's a piece you're missing is the data contract attributes If you make a your class like:

您缺少的一个部分是数据合同属性如果您创建一个类,例如:

[DataContract]
public class RecipeInformation
{
    [DataMember]
    public string name { get; set; }
}

These attributes are found in System.Runtime.Serialization, and the Json parser (Json.NET) uses them to (help) deserialize the model.

这些属性位于 System.Runtime.Serialization 中,Json 解析器 (Json.NET) 使用它们来(帮助)反序列化模型。

回答by itsstephyoutrick

You can try doing something like this and use the jquery param method

你可以尝试做这样的事情并使用 jquery param 方法

    var postData = {
        name : 'name'
    }

    $('#testPostMethod').bind("click", GeneralPost);
    function GeneralPost() {
        $.ajax({
            type: 'POST',
            url: '../api/NewRecipe',
            data: $.param(postData,true),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json'
        });
    }

回答by Yaur

Binding in API controllers is a little on the strange side. I believe:

API 控制器中的绑定有点奇怪。我相信:

public void Post([FromBody]RecipeInformation information)

with

var dataJSON = { name: "test" };

should work, and will definitely work if you just pass it as form data.

应该可以工作,如果你只是将它作为表单数据传递,肯定会工作。

回答by RobLudlmsFrn

I found the problem with help from Microsoft DocsUse JS code as mentioned

我在Microsoft Docs 的帮助下发现了问题 使用 JS 代码如上所述

$.post('api/updates/simple', { "": $('#status1').val() });

What I missed was adding empty property name, so what OP needs to do is{"":data:JSON.stringify(dataJSON)},instead of data:JSON.stringify(dataJSON),

我错过的是添加空属性名称,所以 OP 需要做的是{"":data:JSON.stringify(dataJSON)},而不是data:JSON.stringify(dataJSON),

回答by Rai Ahmad Fraz

$("#updateuser").click(function () {

$("#updateuser").click(function () {

        var id = $("#id").val();
        var dataJSON = $("#username").val();

        alert("" + dataJSON);

        $.ajax({


            url: 'http://localhost:44700/api/Home/' + id,
            type: 'PUT',
            data: JSON.stringify(dataJSON),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',

            success: function (data, textStatus, xhr) {
                $.each(data, function (key, val) {
                    $("<li>" + val + "</li>").appendTo($("#names"));
                })
            },
            error: function (xhr, textStatus, errorThrown) {
                alert('Error in Operation');
            }

            })

    })