在这里,把它放在你的视野中:
<ul>
<li>Mobile
<ul>
<li>Cellphones</li>
<li>Mobile Accessories</li>
</ul>
</li>
<li>Camera
<ul>
<li>Camcorder</li>
<li>Camera Accessories</li>
<li>SLRs</li>
<li>Photo Printers</li>
</ul>
</li>
<li>Computers
<ul>
<li>Laptops</li>
<li>Memory Cards</li>
<li>Monitors</li>
<li>RAM</li>
<li>Computer Accessories</li>
</ul>
</li>
</ul>
虽然这就是你所要求的,但我认为你想要更多的东西。
由于您的问题或您的任何尝试没有任何具体内容,因此在以下解决方案中做出了几个假设。
班级:
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public List<Category> Subcateogries { get; set; }
public Category()
{
Subcateogries = new List<Category>();
}
}
控制器:
public ActionResult Index()
{
//The Data
var categories = new List<Category>
{
new Category { Id = 0, Name = "Mobile" },
new Category { Id = 21, Name = "Cellphones" },
new Category { Id = 22, Name = "Mobile Accessories" },
new Category { Id = 0, Name = "Camera" },
new Category { Id = 55, Name = "Camcorder" },
new Category { Id = 60, Name = "Camera Accessories" },
new Category { Id = 61, Name = "SLRs" },
new Category { Id = 63, Name = "Photo Printers" },
new Category { Id = 0, Name = "Computers" },
new Category { Id = 65, Name = "Laptops" },
new Category { Id = 67, Name = "Memory Cards" },
new Category { Id = 69, Name = "Monitors" },
new Category { Id = 70, Name = "RAM" },
new Category { Id = 71, Name = "Computer Accessories" }
};
var GroupedData = new List<Category>();
foreach(var category in categories)
{
if(category.Id == 0)
{
GroupedData.Add(category);
}
else
{
GroupedData.Last().Subcateogries.Add(category);
}
}
return View(GroupedData);
}
看法:
@model List<Category>
<h2>Categories</h2>
<ul>
@foreach (var topCategory in Model)
{
<li>@topCategory.Name
<ul>
@foreach (var subCategory in topCategory.Subcateogries)
{
<li>@subCategory.Name</li>
}
</ul>
</li>
}
</ul>
这是假设起始列表(在这种情况下为类别)是您想要的顺序。在创建GroupedData时,我还通过重用原始列表项来走捷径。还假设永远只有两个级别。
可以重构视图以利用部分视图并处理多个级别,但这不是问题的一部分。