I have the following setup
HTML
$.ajax({
url: 'Transaction/updateTransaction',
data: saveDataObject,
}).done(function (e) {
// done
});
Which shows in the Network tab that it's sending the correct data
Querystring Parameters
key:2445
transactionDescription:Description Block
transactionToType[0][transactionToTypeKey]:1
transactionToType[0][transactionKey]:2445
transactionToType[0][transactionValue]:51.25
transactionToType[0][transactionTypeKey]:10
transactionToType[1][transactionToTypeKey]:2
transactionToType[1][transactionKey]:2445
transactionToType[1][transactionValue]:10.5
transactionToType[1][transactionTypeKey]:1
Controller
public class TransactionSave
{
public int key { get; set; }
public string transactionDescription { get; set; }
public List<TransactionToTypeSave> transactionToType { get; set; }
}
public class TransactionToTypeSave
{
public int transactionKey { get; set; }
public int transactionToTypeKey { get; set; }
public int transactionTypeKey { get; set; }
public decimal transactionValue { get; set; }
}
public int updateTransaction(TransactionSave transactionSave)
{
}
When doing a breakpoint in updateTransaction I can see transactionSave has all the data (key and description), and the transactionToType list has two items as expected, however, both of these list items, all of the values are 0.
e.g.
key:2445
transactionDescription: Description Block
transactionToType [
transactionToTypeKey:0
transactionKey:0
transactionValue:0
transactionTypeKey:0
], [
transactionToTypeKey:0
transactionKey:0
transactionValue:0
transactionTypeKey:0
]
What am I doing wrong to pass lists inside objects across ajax?
Thanks
It is failing because your ajax call is making a GET request.
If you do not specify the type proeprty when you use $.ajax
method, it will make a GET call. For a GET call, the data will be appended as querystring key value items to the url you are making the ajax call to.
When sending a complex object which has child properties of other types, you should consider doing a POST request. query strings has a limit based on the browser. When the request is POST type, the data will be send in the request body.
This should work.
var saveDataObject =
{
key: 124,
transactionDescription:"My desc",
transactionToType: [{
transactionKey: 111,
transactionTypeKey: 164,
transactionValue:23.34
}
]
};
$.ajax({
type:'post',
url: '@Url.Action("updateTransaction","Transactions")',
contentType:"application/json",
data: JSON.stringify(saveDataObject)
}).done(function(e) {
console.log(e);
});
Make sure you marked your action method with [HttpPost] attribute
[System.Web.Mvc.HttpPost]
public ActionResult updateTransaction(TransactionSave transactionSave)
{
return Json(transactionSave);
}
Now it will send "application/json" as the contentType for the ajax request and the json stringified version of the js object will be in the request body. The model binder will be able to map the posted data to your object