-1

I'm trying to send some data with an Ajax Post request. 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

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"

If I try the same thing with a string, it won't print the string and just leaves the output like "Funziona: "

Why isn't my code reciving any data? Is there anything I'm doing wrong? Thanks.

Dmitriy Popov
  • 2,150
  • 3
  • 25
  • 34
Synapsis
  • 667
  • 1
  • 5
  • 19

2 Answers2

0

Try removing "data: " and changing "url: " to: { value: "~/Controller/Method?saluto=true" }).

Dmitriy Popov
  • 2,150
  • 3
  • 25
  • 34
  • I tryed your method and it works but if I try to send a bigger string it won't work. The status of the request will still return an error – Synapsis Jul 17 '19 at 14:23
0

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? for more information.

phuzi
  • 12,078
  • 3
  • 26
  • 50