我正在尝试如下绘制我的网站地图
<ul>
<li>Cat1</li>
<li>Cat2
<ul class='sub2'>
<li>Cat21</li>
<li>Cat22</li>
<li>Cat23
<ul class='sub23'>
<li>Cat231</li>
<li>Cat232</li>
<li>Cat233
<ul class='sub233'>
<li>Cat2331</li>
<li>Cat2332</li>
<li>Cat2333</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li>Cat3
<ul class='sub3'>
<li>Cat31</li>
<li>Cat32</li>
<li>Cat33</li>
</ul>
</li>
<li>Cat4</li>
</ul>
地图提供者是 PostCategory 对象的列表
List<PostCategory> MapProvider=new List<PostCategory>();
///....MapProvider.add(...);
CategoryMapViewModel siteMap=new CategoryMapViewModel(MapProvider);
var map=siteMap.Map.ToString();
和 PostCategory 对象
public class PostCategory{
[Key]
public int? CategoryId{get;set;}
[StringLength(20/*50*/,MinimumLength=3)]
public string Name{get;set;}
[StringLength(250)]
public string Description { get; set; }
//relationship
public int? IdPostCategoryParent { get; set; }
}
我写了一些东西,但它不适用于子类别的子类别:例如:它适用于 sub2 但不适用于 sub23、sub332、sub....
这是我的 CategoryMapViewModel 类
public class CategoryMapViewModel
{
public HtmlString Map { get; private set; }
private List<int?> TakenIds = new List<int?>();
public CategoryMapViewModel(List<PostCategoryModels> categoriesModels)
{
string map = "";
map = BuildCategoriesMap(categoriesModels, map);
this.Map = new HtmlString(map);
}
private string BuildCategoriesMap(List<PostCategoryModels> categories, string map)
{
if (categories != null && categories.Count > 0)
{
map += "<ul>";
foreach (PostCategoryModels cat in categories)
{
if ((!cat.CategoryId.HasValue) || (cat.CategoryId.HasValue && (!TakenIds.Contains(cat.CategoryId))))
{
map += "<li>" + cat.Name;
List<PostCategoryModels> subCats = categories.Where(c => c.IdPostCategoryParent == cat.CategoryId).ToList();
if (subCats.Count() > 0)
{
//map += BuildCategoriesMap(subCats, map);
//BuildCategoriesMap(subCats, map);
map += BuildCategoriesMap(subCats, "");
}
map += "</li>";
}
TakenIds.Add(cat.CategoryId);
}
map += "</ul>";
}
return map;
}
}
我错了吗 ?有人可以给我最好和最简单的方法吗?如果是,请这样做!亲切的问候!