.net mvc DropDownList 下拉框_无限级分类
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;" })
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。