码迷,mamicode.com
首页 > Web开发 > 详细

.net mvc DropDownList 下拉框_无限级分类

时间:2014-12-27 17:35:34      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:.net   mvc   dropdownlist   

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;" })


技术分享

.net mvc DropDownList 下拉框_无限级分类

标签:.net   mvc   dropdownlist   

原文地址:http://blog.csdn.net/ycwol/article/details/42193589

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!