Question

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.

No correct solution

OTHER TIPS

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!');
    } 
});

try this

$.ajax({
        url: '/api/Chat/New',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify({ id : 10})
    });

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top