C# – AJAX post data is null when it reaches the ASP.NET Core 2.1 controller

ajaxasp.net-corec++jquerypost

I'm posting data to an ASP.NET Core MVC 2.1.2 page using this jQuery code:

function OnCountryChange() {
    $.ajax({
        url: "/OnCountryChange",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        headers: {
            "RequestVerificationToken": $('input[name = __RequestVerificationToken]').val()
        },
        data: JSON.stringify({
            sCountryCode: "Test 123"
        })
    });
}

I am receiving the post in the controller with this method:

[HttpPost]
[ValidateAntiForgeryToken]
[Route("/OnCountryChange")]
public IActionResult OnCountryChange([FromBody] string sCountryCode)
{
    logger.LogDebug($"Country code is: {sCountryCode ?? "null"}");

    return Json(sCountryCode);
}

The output printed to the log is:

Country code is: null

The raw request body (viewed using Fiddler) looks like this:

{"sCountryCode":"Test 123"}

Why isn't the data being passed?

Best Solution

I am not familiar with C#,but in your question you have add

contentType: "application/json; charset=utf-8"

in your Ajax method which means the data parameter is json format,so you need to access as json object instead of access string directly.

Two ways to solve it:

a. Change your C# controller method to access like a json object

b. Send Ajax parameter without json,code similar to below:

function OnCountryChange() {
    $.ajax({
        url: "/OnCountryChange",
        type: "POST",
        datatype: "json",
        headers: {
            "RequestVerificationToken": $('input[name = __RequestVerificationToken]').val()
        },
        data: {sCountryCode: "Test 123"}
    });
}
Related Question