Xiao Han
Xiao Han

Reputation: 1014

JQuery ajax POST string parameter, MVC action method get null

I have seen quite a few posts online regarding this kind of problem and tried different approach, e.g. JSON.stringify the parameter, but none of them works on mine case.

I thought it should be a really simple and straight forward coding experience. But couldn't figure out what I did wrong.

Here is my JQuery code:

$(document).ready(function () {
    $('#SendEmails').click(function () {
        var emails = $("#EmailList").val();     

        $.ajax({
            url: '/Requests/SendEmails',
            type: "POST",
            data: { 'emails': emails },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                alert(response.responseText);
            },
            error: function (response) {
                alert(response.responseText);
            },
            failure: function (response) {
                alert(response.responseText);
            }
        })
    })
})

And my action method is like:

[HttpPost]
public string SendEmails(string emails)
{
    return "Good";
}

I always get null in action method when I debug the code.

But if I change the url to this:

url: '/Requests/SendEmails?emails=' + emails,

and remove

data: { 'emails': emails },

it will work.

Anyone could point me what is wrong with the original code? I don't think .Net Core 2.x should make any difference right?

Thank you.

Upvotes: 3

Views: 8520

Answers (2)

Xiao Han
Xiao Han

Reputation: 1014

Finally, after tried many combinations I found below code works after changed:

  1. make variable JSON.stringify
  2. add [FromBody] in action method

Thanks for Arunraja's tips, [FromBody] is a must to have to read string type parameter from body.

$(document).ready(function () {
    $('#SendEmails').click(function () {
        var emails = $("#EmailList").val();     

        $.ajax({
            url: '/Requests/SendEmails',
            type: "POST",
            data: JSON.stringify(emails),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                alert(response.responseText);
            },
            error: function (response) {
                alert(response.responseText);
            },
            failure: function (response) {
                alert(response.responseText);
            }
        })
    })
})

[HttpPost]
public string SendEmails([FromBody]string emails)
{
    return "Good";
}

Upvotes: 10

Arunraja A
Arunraja A

Reputation: 184

To pass primitive type in the body, then you have to add [FromBody] in front of your primitive type parameter in your WebAPI controller method.

[HttpPost]
public string SendEmails([FromBody]string emails)
{
    return "Good";
}

Upvotes: 4

Related Questions