4

POST form variables to simple parameters of a Web API method in ASP.NET MVC 4 Web API

$.ajax({
    url: 'api/products',
    type: 'POST',
    data: { Id: 2012, Name: 'test', Category: 'My Category', Price: 99.5 },
    dataType: 'json',
    success: function (data) {
        alert(data);
    }
});

but its not working how to do this?

4
  • 1
    I do exactly what you've used above, but use .ashx files to handle calls and use Context.Request.Form[] to get the post data. It has the advantage that ashx files are nice and fast. Commented Nov 15, 2012 at 12:48
  • @Archer i have used the answer below ... is that answer worthy to use ? Commented Nov 15, 2012 at 13:24
  • If it works for you then yes. I tried various methods of handling .Net calls from Javascript and ended up doing the above. I was just letting you know about it as I find it simple, albeit a bit "old school". Commented Nov 15, 2012 at 13:28
  • Can you post your ApiController? Commented Feb 20, 2014 at 21:26

1 Answer 1

1

Use below code it will work. Only change I have made is in data parameter where I am doing JSON.stringify(), faced with same issue quite a few months back. Basically it expects a string which can be parsed to JSON.

$.ajax({
    url: 'api/products',
    type: 'POST',
    data: JSON.stringify({ Id: 2012, Name: 'test', Category: 'My Category', Price: 99.5 }),
    dataType: 'json',
    success: function (data) {
        alert(data);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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