【发布时间】:2014-03-08 05:22:14
【问题描述】:
我有这个剃刀观点:
@using Order.Models
@model CategoriesViewModel
@{
ViewBag.Title = "Categories";
}
@using (Html.BeginForm())
{
<div class="panel-group">
@foreach (var p in Model.Categories)
{
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#@p.ID.ToString()">
@p.Name
</a>
</h4>
</div>
<div id="@p.ID.ToString()" class="panel-collapse collapse">
<div class="panel-body">
@foreach (var m in p.Items)
{
//put items data here
}
</div>
</div>
</div>
}
</div>
}
使用这个视图模型:
namespace Order.Models
{
public class CategoriesViewModel
{
public IEnumerable<RestCategories> Categories;
public List<List<RestItem>> Items;
}
}
控制器动作是:
[HttpGet]
public ActionResult Categories()
{
List<List<RestItem>> ItemsForCategory = new List<List<RestItem>>();
API OneApi = new API();
IEnumerable<RestCategories> itemsResult = API.GetCategoryResults("test", "test");
if (itemsResult.Count() > 0)
{
foreach (RestCategories cat in itemsResult)
{
ItemsForCategory.Add(OneApi.GetItemsForCategory(ConfigurationManager.AppSettings["Key1"], ConfigurationManager.AppSettings["Key2"], cat.ID.ToString()));
}
}
CategoriesViewModel modelCat = new CategoriesViewModel
{
Categories = itemsResult
.OrderBy(i=>i.Order),
Items = ItemsForCategory
};
return View(modelCat);
}
现在,我不确定这是否是正确的做法,但我想显示类别,并且在这些类别中我想显示该类别中的项目。我可以获取列表中的所有项目,正如您在视图中看到的那样,我正在尝试遍历 Items 集合,但我无法从模型中获取 Items 属性。我也试过这种方法
@foreach(Model.Items.Where(n=>n.CategoryId = p.ID) 中的变量 m)
但还是什么都没有。
【问题讨论】:
-
我不认为你需要在你的物品上列出
-
是的,我可以看到类别,但看不到项目。我使用的方法是返回项目列表,然后将其放入每个类别 ID 的新列表中,这就是我使用双列表的原因。 @MattBodily 感谢帮助我
-
如果你只返回一个列表
,其中包含一个列表中的所有项目,第二个 foreach 将为你解析它们。您无需将它们放入第二个列表中
标签: c# asp.net-mvc razor