ASP.NET:下拉列表asp.net mvc 5中的类别和子类别

时间:2016-12-26 17:55:06

标签: c# asp.net-mvc drop-down-menu

I have a table with: 
 tbl_Category
  Id        |           Name            |       ParentID

  1                 Category 1                      0
  2                 Category 2                      0
  3                 Subcategory 11                  1
  4                 Subcategory 12                  1
  5                 Subcategory 21                  2
  6                 Subcategory 211                 5
  7                 Subcategory 22                  2
.........

How do I return it in a dropdownlist in the below format:

Category 1
--Subcategory 11
--Subcategory 12
--Subcatgory 13
Category 2
--Subcategory 21
----Subcategory 211
----Subcategory 212
--Subcategory 22
--Subcatgory 23
Category 3
--Subcategory 31
--Subcategory 32

2 个答案:

答案 0 :(得分:0)

您可以在文字中使用html,例如尝试:

Category1
 Subcategory11

等。这样,文本将根据类别级别缩进到右侧

答案 1 :(得分:0)

Html.DropDownListFor辅助方法能够渲染组中的项目。您只需为每个Group指定SelectListItem属性。

var group1 = new SelectListGroup {Name = "Category 1"};
var group2 = new SelectListGroup { Name = "Category 2" };

var options= new List<SelectListItem>
{
    new SelectListItem {Value = "1", Text = "Subcategory 11", Group = group1},
    new SelectListItem {Value = "2", Text = "Subcategory 12", Group = group1},
    new SelectListItem {Value = "3", Text = "Subcategory 21", Group = group2}
};

使用辅助方法

@Html.DropDownListFor(s=>s.SomeProperty,options)

DropDownList助手

@Html.DropDownList("MySelectName", options)

获取数据?

如果您使用Entity框架进行数据访问,则可以执行此代码以在操作方法中获取分组数据。

var db = new YourDbContextHere();  // Replace your db context class here
var parentsDictionary = db.Categories 
                          .ToDictionary(d => d.Id, v => v.Name);

var groups = db.Categories.Select(x => x.Name)
        .Select(f => new SelectListGroup() { Name = f }).ToList();

var itemsWithParents = (from c in db.Categories
                        join p in db.Categories
                        on c.ParentId equals p.Id
                        select new { Id = c.Id, 
                                     Text = c.Name, 
                                     ParentId = c.ParentId }).ToList();

var groupedData = itemsWithParents
                   .Where(f => f.ParentId != 0)
                   .Select( x => new SelectListItem
                               {
                                 Value = x.Id.ToString(),
                                 Text = x.Text,
                                 Group = groups
                                        .First(a => 
                                                a.Name == parentsDictionary[x.ParentId])
                               }).ToList();
ViewBag.GroupedCategory= groupedData;
return View();

假设您没有视图模型,我使用ViewBag传输数据。

现在在您看来,使用DropDownList辅助方法

  @Html.DropDownList("SelectedCategory",ViewBag.GroupedCategoryas List<SelectListItem>)