Search code examples
jquery.netpostasp.net-core-mvc

ASP.NET Core 8 MVC: POSTing from jQuery all values are null in controller


I'm calling a controller endpoint from jQuery and the problem is all parameters are received as null by the endpoint.

javascript:

$.ajax({
    url: '/Test/SendEmailWithCode',
    type: "POST",
    async: false,
    contentType: "application/json",
        data: JSON.stringify({
            mailTo: mailTo,
            subject: subject,
            message: message,
            digit32: digit32,
            digit16: digit16,
            code: encrypt(generateCode(), digit32, digit16).toString()
        }),
    success: function (data) {
        $("#userCodeData").val("data");
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {

        }
    }
});

Controller:

[HttpPost]
public JsonResult SendEmailWithCode(string mailTo, string subject, string message, string digit32, string digit16, string code)
{
    var result = _emailService.SendEmailWithCode(mailTo, subject, message);

    return new JsonResult(result);
}

Apparently everything's fine, but no way, the values are always null in the controller. What can I try next?

Edit 1

The weird thing is that if I replace POST call by GET (type: "GET" in javascript + [HttpGet] in controller) values are received correctly, but that's not the case, I'm sending an email in controller, so the type of the call should be POST.


Solution

  • Try to modify your ajax like below :

    $.ajax({
        url: '/Test/SendEmailWithCode',
        type: "POST",
        data:{
                mailTo: mailTo,
                subject: subject,
                message: message,
                digit32: digit32,
                digit16: digit16,
                code: encrypt(generateCode(), digit32, digit16).toString()
            },
        success: function (data) {
            $("#userCodeData").val("data");
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
    
            }
        }
    });
    

    result:

    enter image description here