ToneSwitch ToneSwitch - 1 year ago 82
jQuery Question

Sending JSON object to Web API failure

I am trying to send jQquery object through ajax to a Web API controller.

Here's my jquery code:

var CurrentOrder = [];
var lineItem = { 'rowid': '34', 'quantity': '4', 'comment': 'somecomment' ,
'rowid': '22', 'quantity': '5', 'comment': 'somecomment1'};


type: 'PUT',
data: JSON.stringify({ SessionCart: CurrentOrder }),
contentType: 'application/json; charset=utf-8',
url: '/api/Cart/UpdateCart/',
//traditional: true,
beforeSend: function () {
success: function () {
$('.loader').attr('style', 'display:none');
error: function () {
$('.loader').attr('style', 'display:none');
alert('Current Order could not be updated. Please Try again.')

Here's my model:

public class Cart
public string rowid { get; set; }
public string quantity { get; set; }
public string comment { get; set; }


And the controller:

[HttpPut, HttpDelete]
public HttpResponseMessage UpdateCart([FromUri] List<Cart> SessionCart)

//do sth

The problem is the controller gets hit but the parameter
count is always 0. I have tried not to stringify the object, using quotes to wrap the object, passing a single object and not an array and a bunch of other things. None of these worked. Any help would be much appreciated.

Answer Source

[FromUri] should either not be there at all or change it to [FromBody] -

[FromUri] will be looking at the querystring for the data vs the PUT body

Also, it looks like you should be setting your data to:

data: JSON.stringify(CurrentOrder),

This, plus what Matteo1010 suggests.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download