Reputation: 48482
On the home page of my app, I'm making an AJAX call to get a large amount of data that will be needed in various parts of my app. The call looks as follows:
var url = "/Taxonomy/GetTaxonomyList/"
$.getJSON(url, { includeOverrides: true }, function (jsonData) {
}).success(function (jsonData) {
sessionStorage.taxonomyWithOverrides = jsonData;
}).fail(function (jqXHR, textStatus, errorThrown) {
...
});
This AJAX call is calling a C# method that is returning a JSONResult. This part seems to be working ok because I am getting the data I expect.
In another page I'm attempting to read this data as follows:
var taxonomy = [];
if (typeof (Storage) !== "undefined") {
jsonData = sessionStorage.taxonomyWithOverrides;
$.each(jsonData, function (key, data) {
taxonomy.push(data.species);
})
} else {
alertify.alert("Storage not supported");
}
However, I'm getting the following JavaScript error:
Uncaught TypeError: Cannot use 'in' operator to search for '182782' in [object Object], [object Object],...
Clearly I'm doing something wrong. But, I don't have a great deal of experience with this so I'm not sure where to look.
Here is my c# method that returns the JSON data:
public JsonResult GetTaxonomyList(bool includeOverrides)
{
try
{
var taxonomyList = this.TaxonomyData.GetList(this.AccountRowId,0,string.Empty,true, includeOverrides)
.Select(row => row.CommonName + " - " + row.ScientificName)
.ToList();
var jsonList = (from species in taxonomyList
select new { species }
).OrderBy(row => row.species);
return Json(jsonList, JsonRequestBehavior.AllowGet);
}
catch (System.Exception exception)
{
...;
}
}
Upvotes: 0
Views: 92
Reputation: 318302
You stored a string, when you get it back from storage you have to parse it back to an object, as $.each
doesn't work on strings, but objects and arrays
var taxonomy = [];
if (typeof (Storage) !== "undefined") {
jsonData = JSON.parse( sessionStorage.taxonomyWithOverrides || '[]');
$.each(jsonData, function (key, data) {
taxonomy.push(data.species);
})
} else {
alertify.alert("Storage not supported");
}
I'm assuming you have a stringify() method that is chainable, otherwise change
jsonData.stringify();
to
JSON.stringify(jsonData);
Upvotes: 1