1、数据库设计:
id:int
name:string
pid:int //父级id(顶级菜单默认为0)
2、Controller:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcTest.Models; namespace MvcTest.Controllers { [ValidateInput(false)] public class HomeController : Controller { private testEntities db = new testEntities(); [LoginFilter] public ActionResult Index() { BindDropDownList(); return View(); } //绑定顶级分类 private void BindDropDownList() { List<SelectListItem> select1 = new List<SelectListItem>(); var one = from c in db.Categories where c.pId == 0 select c; foreach (var b in one) { string name = b.name; string id = b.id.ToString(); select1.Add(new SelectListItem { Text = "> " + name, Value = id }); int sonparentpid = int.Parse(id); string blank = " ┠ "; //递归子分类方法 BindNode(sonparentid, blank, select1); } ViewBag.caList = new SelectList(select1, "Value", "Text"); } //绑定子分类 private void BindNode(int pid, string blank, List<SelectListItem> select1) { var two = db.Categories.Where(c => c.pId == pid); foreach (var c in two) { string zname = blank + c.name; string zid = c.id.ToString(); select1.Add(new SelectListItem { Text = zname, Value = zid }); int sonparentid = int.Parse(zid); string blank2 = blank + "━"; BindNode(sonparentid, blank2, select1); } } } }
3、view:
@Html.DropDownListFor(a => a.caId, ViewBag.caList as IEnumerable<SelectListItem>,"---请选择---" , new { style = "width: 120px;" })
时间: 2024-10-15 13:05:30