0

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.

3
  • Try taking out the dataType: 'json' line. You're not receiving an object in your controller, just a primitive type. Commented Mar 4, 2014 at 2:17
  • I have tried that and nothing changed at all Commented Mar 4, 2014 at 2:23
  • You said it does hit the controller, just no data? I'm posting an alternative that works for me in this situation Commented Mar 4, 2014 at 2:30

3 Answers 3

1

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!');
    } 
});
Sign up to request clarification or add additional context in comments.

Comments

0

try this

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.