Reputation: 815
My AJAX is not sending data to my http post controller.
My controller:
[Route("api/sendingData")]
public class TestController : ApiController
{
[HttpPost]
public string Post([FromBody] int propertyID)
{
return string.Format("Test");
}
}
My AJAX:
$.ajax(
{
url: "api/sendingData",
type: "POST",
dataType: 'json',
data: {
'propertyID': '1'
},
success: function (result) {
console.debug(result);
alert(result);
},
error: function (xhr, status, p3, p4) {
console.debug(xhr);
var err = "Error " + " " + status + " " + p3;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).message;
alert(err);
}
});
I'm trying to send the propertyID=1
. However, when I debug my controller, it shows propertyID=0
.
Does anyone know what is wrong?
Upvotes: 2
Views: 542
Reputation: 6683
Might look weird but you're only sending one value, not a model, so the stringify is JSON.stringify(value)
var propertyID = 1;
$.ajax({
url: "api/sendingData",
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(propertyID),
success: function (result) {
console.debug(result);
alert(result);
},
error: function (xhr, status, p3, p4) {
console.debug(xhr);
var err = "Error " + " " + status + " " + p3;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).message;
alert(err);
}
});
Also I have removed dataType json because your action method is not returning json but a string. Now I'm getting success.
Upvotes: 2