Reputation: 331
I am working with mvc4 and jQuery, I get a controller action getJson
calling and passing a json list,
public JsonResult GetChildCategories(int id)
{
Category cat = new Category(id);
List<Category> child = new Categories().ToList(cat);
List<Tuple<int, string>> childList = new List<Tuple<int, string>>();
for (int i = 0; i < child.Count; i++)
{
childList.Add(new Tuple<int, string>(child[i].Id, child[i].Name));
}
return Json(childList, JsonRequestBehavior.AllowGet);
}
When calling this action by url, I get output like:
[{"Item1":3,"Item2":"Pulp Devitalizer"},{"Item1":5,"Item2":"Irrigants and conditioners"}]
I am trying to iterate this in each loop, but I can't:
$.getJSON('/Add/GetChildCategories/' + id, function (data) {
$.each(data, function (i, item) {
alert(Item);
$("<li>" + item[i][1] + "</li>").appendTo($('#' + id + ' .category-child'));
});
});
I want to show the string part in li, when alert (item) it shows [object, object]
Upvotes: 0
Views: 150
Reputation: 3723
The usage of item[i][1]
does not make sense. An array of objects is looped with the $.each
function. Argument i refers to the index of the element within the array, item refers to the element within the array (in this case the object). The object, however, has two fields that can be addressed with item.Item1
and Item.Item2
.
Check this fiddle to see an example with your code and notice that item.Item1
returns a value and item[0]
not (undefined).
Hope this will help.
Upvotes: 1