I have having such a hard time getting my json variables out of my json that is retuned from my ajax call to my asp.net mvc controller class. Here is my jquery ajax call:
$.ajax({
url: '@Url.Action("ReturnTotals", "Cart")',
type: 'POST',
datatype: 'json',
success: function (jsonData) {
var totals = $.parseJSON(jsonData);
var cost = totals.cost;
var qty = totals.qty;
$("#totalCost").html(cost);
$("#totalQty").html(qty);
console.log(cost);
console.log(qty);
console.log($.parseJSON(jsonData));
}
});
My first 2 console.logs come back undefined. And the third spits out
[Object { Key="cost", Value=109}, Object { Key="qty", Value=12}]
I have checked that line with jsonlint and it is well formed json. For the line "var cost = totals.cost;" I have tried changing that to "var cost = totals["cost"];" and that didn't do anything.
Here is my server side function:
public string ReturnTotals()
{
CartSummaryModel cart = null;
CartModel m = null;
cart = (CartSummaryModel)cXML.cXML.DeserializeObject(Session["CARTSUMMARY"].ToString(), typeof(CartSummaryModel));
Dictionary<string, double> totals = new Dictionary<string, double>();
totals.Add("cost", cart.TotalCost);
totals.Add("qty", cart.TotalQty);
string totalString = cXML.cXML.SerializeJson( totals );
return totalString;
}
1 Answer 1
There is a default Json serialiser within assp.net mvc that you can use! In fact, I am not trying to discourage you from using your serializer but here is what works for me
public JsonResult ReturnTotals()
{
CartSummaryModel cart = null;
CartModel m = null;
// cart = (CartSummaryModel) Session["CARTSUMMARY"] ;
Dictionary<string, double> totals = new Dictionary<string, double>();
totals.Add("cost", cart.TotalCost);
totals.Add("qty", cart.TotalQty);
return Json(totals,"text/json",JsonBehavour.AllowGet);
}
And jQuery
$(document).ready(function(){
var url='@Url.Action("ReturnTotals", "Cart")';
$.getJSON(url).done(function (jsonData) {
var totals =[]||jsonData;
var cost = totals.cost;
var qty = totals.qty;
$("#totalCost").html(cost);
$("#totalQty").html(qty);
console.log(cost);
console.log(qty);
});
});
total[0].cost