Reputation: 1014
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
Reputation: 1014
Finally, after tried many combinations I found below code works after changed:
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
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