So I have a function in my code, that I'm calling using jQuery's getJSON. Here's the function:
public JsonResult GetItems()
{
var items = (from x in GetAllItems()
select new { x.ItemID, x.ItemType.Name, x.Description })
.ToList();
JsonResult result = Json(items, JsonRequestBehavior.AllowGet);
return Json(result, JsonRequestBehavior.AllowGet);
}
And this is where I'm calling it with jQuery:
$.getJSON('/MyController/GetItems/', function (data) {
// somehow iterate through items, displaying ItemID, Name, and Description
});
But I'm stuck here, I'm not sure what to do. I'd like to iterate through each item, and display the ItemID, Name, and Description in an alert box. But every example I've found just shows how iterate and display items that only have a key and a value, 开发者_如何学运维but my items have move than 2 properties to display.
Try this:
$.getJSON('/MyController/GetItems/', function (data) {
var name, itemId, description;
$.each(data, function(){
name = this.Name;
itemId = this.ItemID;
description = this.Description ;
//You can use these variables and display them as per the need.
});
});
Use firebug to debug your javascript code. There you can see what result you have in your data object if you set a breakpoint in your code. My guess is that should write something like:
$.getJSON('/MyController/GetItems/', function (data) {
for(var i = 0; i < data.length; i++) { // add a breakpoint here
// to see if reach the line and
// the content of data
// do your funky stuff here
}
});
精彩评论