Reputation: 327
My asp.net httpPost is not working from AJAX request.
My controller:
[Route("api/sendData")]
public class TestController : ApiController
{
[HttpPost]
public bool Post(PostData data)
{
return true;
}
}
My PostData:
public class PostData
{
public int Id { get; set; }
}
My AJAX request from html file:
var data = {
Id : 1
};
$.ajax(
{
url: "api/sendData",
type: "POST",
dataType: 'json',
data: data,
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 don't know why it is returning 404 Not Found. Does anybody know what I'm doing wrong?
Thanks
Upvotes: 0
Views: 102
Reputation: 24957
The RouteAttribute
should be apply on top of action method name instead of controller class, so that the action method becomes this:
public class TestController : ApiController
{
[HttpPost]
[Route("api/sendData")]
public bool Post(PostData data)
{
return true;
}
}
If you want to use attribute routing on controller class level, RoutePrefixAttribute
should be used instead.
Additionally, if you want to pass properties inside object model, you need to use JSON.stringify
and set contentType: "application/json"
as you want to send JSON object into action method:
<script>
var data = { Id: 1,
// other properties
};
$.ajax({
url: "api/sendData",
type: "POST",
contentType: "application/json",
dataType: 'json',
data: JSON.stringify(data),
success: function (result) {
console.debug(result);
alert(result);
},
error: function (xhr, status, p3, p4) {
// error handling here
}
});
</script>
Upvotes: 1