【发布时间】:2016-07-21 17:48:41
【问题描述】:
我有一个名为 Category 的模型,它具有如下递归(父子)关系:
public class Category: ITreeNode<Category>
{
public byte Id { get; set; }
public byte? ParentId { get; set; }
public string Name { get; set; }
public Category Parent { get; set; }
public IList<Category> Children { get; set; }
}
我想生成一个下拉列表,该下拉列表根据父子关系进行分组,我还可以按如下方式选择父组 - 基本上我想从父级缩进子级:
<select name="Category" id="Category">
<option value="0">All</option>
<option value="1">Cars</option>
<option value="2">--Toyota</option>
<option value="3">--Nissan</option>
<option value="4">Fruits</option>
<option value="5">--Apples</option>
<option value="6">--Oranges</option>
</select>
我的Table数据如下:
Id | ParentId | Name
----------------------
1 | null | Cars
2 | 1 | Toyota
3 | 1 | Nissan
4 | null | Fruits
5 | 4 | Apples
6 | 4 | Oranges
目前我有以下 LINQ 查询,但它只是生成一个按 id 排序的普通下拉列表。
public IEnumerable<SelectListItem> GetCategoriesSelectList()
{
var categories = new List<SelectListItem>
{
new SelectListItem() {Value = "0", Text = "All" }
}.Concat(_context.Category.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
}).OrderBy(x => x.Value).ToList());
return categories
}
如何修改 LINQ 查询,以便在使用 Html.DropDownListFor 呈现时正确分组和缩进。
我尝试修改我的原始选择列表以实现如下某种树,但我被困在 EnumerateNodes 方法上。下面的原件用于打印我从以下站点http://www.codeproject.com/Articles/23949/Building-Trees-from-Lists-in-NET 提取的 ul 列表。我如何遍历它并返回每个项目,如果它是一个孩子,然后将 -- 附加到名称并添加到我的选择列表中?
public IEnumerable<SelectListItem> GetCategoriesSelectList()
{
IList<Category> listOfNodes = GetListOfNodes();
IList<Category> topLevelCategories = TreeHelper.ConvertTOForest(listOfNodes);
var cats = new List<SelectListItem>
{
new SelectListItem { Value = "0", Text = "All"}
};
foreach(var category in topLevelCategories) {
var catName = EnumerateNodes(category);
cats.Add(new SelectListItem { Value = category.Id.ToString(), Text = catName });
}
return cats;
}
private List<Category> GetListOfNodes()
{
List<Category> sourceCategories = _context.Category.ToList();
List<Category> categories = new List<Category>();
foreach (Category sourceCategory in sourceCategories)
{
Category s = new Category();
s.Id = sourceCategory.Id;
s.Name = sourceCategory.Name;
if (sourceCategory.ParentId != null)
{
s.Parent = new Category();
s.Parent.Id = (int)sourceCategory.ParentId;
}
categories.Add(s);
}
return categories;
}
private static string EnumerateNodes(Category parent)
{
if (category.Children.Count > 0) {
Response.Write("<ul>");
foreach(Category child in category.Children) {
EnumerateNodes(child);
}
Response.Write("</ul>");
}
Response.Write("</li>");
}
【问题讨论】:
-
你到底卡在哪里了?如果你想知道如何创建下拉列表,你可能想看看Best programming practice of using DropDownList in ASP.Net MVC。
-
@win 我知道如何创建列表,是如何编写 LINQ 将它们分组和缩进。
-
@Win 不是重复的。我的问题略有不同。它与构建下拉列表有关。
标签: c# linq asp.net-mvc-5 html.dropdownlistfor recursive-query