Ajax调用MVC控制器

I'm trying to pass some data with ajax call to a c# mvc controller. Even though the task should be straight forward, I am unable to get the mvc controller to read the data I'm passing through the ajax call....

I've implemented the following code within my MVC controller

[HttpPost]
public string tt(string o)
{            
    return o;
}

[HttpPost]
public string tt2(string o)
{
    return "lala";
}

And I'm triggering the following ajax calls from the browser

$.ajax({
    url: "/Home/tt2",
    type: "POST",
    contentType: "application/json;",
    data: JSON.stringify({ o: 'asdas'}),     
    success: function(e){console.log(e+'    correct');},
    error: function(e){console.log(e+'    incorrect');}
});

$.ajax({
    url: "/Home/tt",
    type: "POST",
    contentType: "application/json;",
    data: JSON.stringify({ o: 'asdas'}),     
    success: function(e){console.log(e+'    correct');},
    error: function(e){console.log(e+'    incorrect');}
});

As a result when running the first ajax call the result is

lala    correct

And for the second ajax call, the result is

undefined    correct

In the mean time these are some stuff I tried

  • Adding dataType: "json", to the ajax call
  • Changing the string data from {o: 'asdas'} to 'asdas'
  • Removing the JSON.stringify
  • Adding the charset=utf-8 to the contentType
  • Changing the ajax call type and MVC controller method from POST to GET to PUT
  • Changing the MVC controller method parameter from string to int
  • Removing the error method from the ajax call
  • Changing the data from data: {o: 'asdas'} to data: {"o":"asdas"}
  • Changing the data from data: {"o":"asdas"} to data: JSON.stringify({"o":"asdas"})

I know that simple string or int can be passed through the URL as query strings but it would be an issue when passing a list of objects..

Something aside is that the call is being done correctly to the URL because when I set a breakpoint within the called method, it does get triggered but the parameter always is null..

Any thoughts on how to make ajax call work?

Your request should be like this:

$.ajax({
            url: '@Url.Action("tt", "Home")',
            data: {
                "o": "asdasdas"
            },
            cache: false,
            type: "POST",
            success: function (response) {

            },
            error: function (xhr) {
            }
            });

try:

[HttpPost]
public string tt([FromBody]string o)
{            
    return o;
}