Reputation: 7984
I have a simple ajax call that is not sending data correctly. What am I doing wrong? Here is the AJAX:
$.ajax({
url: '/api/Chat/New',
type: 'POST',
dataType: 'json',
data: { id : 10}
});
and here is my controller:
public class ChatController : BaseApiController
{
//
// GET: /Chat/
[HttpPost]
public int New(int id = -1)
{
return id;
}
}
BaseApiController
is my own controller that has DB context in it and it inherits from ApiController. I cannot get data to send across the wire at all. New() just returns -1 every time.
Upvotes: 0
Views: 1080
Reputation: 3816
Please take a look at the answer of the following post http://forums.asp.net/t/1939759.aspx?Simple+post+to+Web+Api
Basically, Web API Post accept only one parameter, it can be a primitive type or a complex object.
Change your ajax request to the following
$.ajax({
url: '/api/Chat/New',
type: 'POST',
data: { '' : 10}
});
Then change your controller as follows
[HttpPost]
public int New([FromBody]int id = -1)
{
return id;
}
If it's a complex object like a ViewModel
, you don't need to use FromBody
You can read more about why this is required by reading "Using[FromBody]" section in the following article.
http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
Upvotes: 0
Reputation: 6423
try removing the data type from your ajax call. Something like this
$.ajax({
url: '@Url.Action("New", "Chat")',
type: 'post',
cache: false,
async: true,
data: { id: 10 },
success: function(result){
// do something if you want like alert('successful!');
}
});
Upvotes: 1
Reputation: 1377
try this
$.ajax({
url: '/api/Chat/New',
type: 'POST',
dataType: 'json',
data: JSON.stringify({ id : 10})
});
Upvotes: 0