简体   繁体   English

无法通过 POST 请求 AJAX 传递/接收值

[英]Can't pass/receive values with POST request AJAX

I'm trying to send some data with an Ajax Post request.我正在尝试使用 Ajax Post 请求发送一些数据。 The code of the request is the following:请求的代码如下:

$.ajax({
    url: "[url of page]",
    type: "POST",
    data: {saluto: true},
    dataType: 'text',
    success: function (response) {
        alert("successful" + response);
    },
    error: function () {
        alert("error");
    }
});

So in this case I should receive saluto = true所以在这种情况下,我应该收到saluto = true

This is the Backend code:这是后端代码:

[HttpPost("Test")]
public async Task<string> testHelloWorld(bool saluto)
{

    try
    {
        string testString = "Funziona";
        Console.Write(testString + ": " + saluto + "\n");
        return testString;
    }
    catch (Exception ex)
    {
        Log.Error("API(CallToXML) - Exception", ex);
        return null;
    }
}

So if saluto = true My console should print "Funziona: True" the OUTPUT tho is "Funziona: False"因此,如果saluto = true我的控制台应该打印"Funziona: True"则 OUTPUT 为"Funziona: False"

If I try the same thing with a string, it won't print the string and just leaves the output like "Funziona: "如果我用字符串尝试同样的事情,它不会打印字符串,只会留下像"Funziona: "这样的输出

Why isn't my code reciving any data?为什么我的代码没有收到任何数据? Is there anything I'm doing wrong?有什么我做错了吗? Thanks.谢谢。

尝试删除"data: "并将"url: "更改为: { value: "~/Controller/Method?saluto=true" })

You'll need to change the signature of your action to您需要将操作的签名更改为

public async Task<string> testHelloWorld([FromBody]bool saluto)

By default the model binder looks for simple types in the request parameters not the body of the request.默认情况下,模型绑定器在请求参数而不是请求正文中查找简单类型。

Take a look Tadej's answer to Why do we have to specify FromBody and FromUri?看看Tadej为什么我们必须指定 FromBody 和 FromUri 的回答? for more information.想要查询更多的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM