2016-12-26 69 views
-3
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 

回答

0

您可以使用HTML在你的文本,以便例如嘗試:

Category1 
 Subcategory11 

等等。這樣的文本將被縮進到正確根據類別級別

+0

我需要得到它在數據庫中,並顯示查看。怎麼做? –

0

幫助器方法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>) 
+0

我需要進入數據庫,使用Model,Controller,View顯示它。 –

+0

我不知道你的數據訪問技術是什麼。所以不能幫助 – Shyju

+0

我使用asp.net mvc 5。模型將從表tbl_Category獲取數據,並顯示查看 –