ASP.NET:类别和子类别的下拉列表中asp.net的MVC 5
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
您可以使用HTML在你的文本,以便例如尝试:
Category1
Subcategory11
等等。这样的文本将被缩进到正确根据类别级别
帮助器方法Html.DropDownListFor
能够渲染组中的项目。您只需要为每个SelectListItem
指定Group
属性。
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)
获取数据的使用情况如何?
如果您使用实体框架进行数据访问,则可以执行此代码以获取操作方法中的分组数据。
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>)
我需要进入数据库,使用Model,Controller,View显示它。 –
我不知道你的数据访问技术是什么。所以不能帮助 – Shyju
我使用asp.net mvc 5。模型将从表tbl_Category获取数据,并显示查看 –
我需要得到它在数据库中,并显示查看。怎么做? –