1、Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Entity;
namespace WebApplication1.Controllers
{
public class DefaultController : Controller
{
public ActionResult CategorysIndex()
{
TreeBind();
return View();
}
private ActionResult TreeBind()
{
List<Categorys> list = GetCategorysList();
List<Categorys> parentList = list.Where(o => o.ParentId == 0).ToList();
List<Categorys> childList = null;
List<SelectListItem> select1 = new List<SelectListItem>();
#region 普通循环输出数据
foreach (var item in parentList)
{
if (item.ClassLayer == 1)
{
select1.Add(new SelectListItem { Value = item.Id.ToString(), Text = item.Title });
childList = list.Where(o => o.ParentId == item.Id).ToList();
foreach (var childs in childList)
{
select1.Add(new SelectListItem { Value = childs.Id.ToString(), Text = "├ " + childs.Title });
for (int i = 1; i <= 2; i++)
{
string name = HttpUtility.HtmlDecode(" ├ " + childs.Title + i.ToString());
select1.Add(new SelectListItem { Value = childs.Id.ToString(), Text = name });
}
}
}
}
#endregion
#region 迭代输出数据
#endregion
ViewData["selCategorys"] = new SelectList(select1, "Value", "Text", "");
return View();
}
private List<Categorys> GetCategorysList()
{
List<Categorys> list = new List<Categorys>();
var jiaydq = new Categorys { Id = 1, ParentId = 0, ClassLayer = 1, Title = "家用电器" };
list.Add(jiaydq);
var diannao = new Categorys { Id = 2, ParentId = 0, ClassLayer = 1, Title = "电脑" };
list.Add(diannao);
var jiaju = new Categorys { Id = 3, ParentId = 0, ClassLayer = 1, Title = "家居" };
list.Add(jiaju);
var dianshi = new Categorys { Id = 4, ParentId = 1, ClassLayer = 2, Title = "电视" };
list.Add(dianshi);
var kongtiao = new Categorys { Id = 5, ParentId = 1, ClassLayer = 2, Title = "空调" };
list.Add(kongtiao);
var diannaozj = new Categorys { Id = 6, ParentId = 2, ClassLayer = 2, Title = "电脑整机" };
list.Add(diannaozj);
var diannaopj = new Categorys { Id = 7, ParentId = 2, ClassLayer = 2, Title = "电脑配件" };
list.Add(diannaopj);
return list;
}
}
}
2、Html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>CategorysIndex</title>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
</head>
<body>
<br /><br /><br />
<table>
<tr>
<td>分类:</td>
<td>@Html.DropDownList("Categorys", ViewData["selCategorys"] as SelectList, new { @class = "form-control", filter = "false" })</td>
</tr>
</table>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication1.Entity
{
public class Categorys
{
public int Id { get; set; }
public string Title { get; set; }
public int ParentId { get; set; }
public int ClassLayer { get; set; }
}
}