Skip to main content
 首页 » 编程设计

c#之使用 getJSON 显示数组

2024年02月23日13cmt

所以我的代码中有一个函数,我正在使用 jQuery 的 getJSON 调用它。这是函数:

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); 
} 

这就是我用 jQuery 调用它的地方:

$.getJSON('/MyController/GetItems/', function (data) { 
    // somehow iterate through items, displaying ItemID, Name, and Description 
}); 

但我被困在这里,我不知道该怎么办。我想遍历每个项目,并在警告框中显示 ItemID、名称和描述。但是我发现的每个示例都只是展示了如何迭代和显示只有一个键和一个值的项目,但我的项目有两个以上的属性要显示。

请您参考如下方法:

试试这个:

$.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.   
    }); 
});