MVC中下拉框的绑定以及递归实现方法总结(转http://hi.baidu.com/yuleboxcn/blog/item/339ae4128483f936dc54017e.html)

Coordinator
Sep 27, 2011 at 8:18 AM
MVC中下拉框的绑定以及递归实现方法总结
2011-04-07 13:21

今天主要谈的就是下拉框普通绑定以及如何实现下拉框的递归绑定。

普通的下拉框的绑定

前台:

<%= Html.DropDownList("houseID", (SelectList)ViewData["DrophouseData"])%>

后台:

//控制层

ViewData["DrophouseData"] = obj.gethouseData();

//Model层

public SelectList getWarehouseData()
        {
            var ItemList = EmpDB.house.Where(StrWhere => StrWhere.EID == 1).OrderBy(OrderField => OrderField.ID);

            List<house> dataList = new List<house>();
            dataList.Add(new house { Warehouse_Name = "=请选择数据=" });
            dataList.AddRange(ItemList);

            SelectList sList = new SelectList(dataList, "ID", "Name");
            return sList;
        }

递归下拉框的绑定

前台:

<%= Html.DropDownList("TypeID", (List<SelectListItem>)ViewData["DropTypeData"])%>

后台:

//控制层

 ViewData["DropTypeData"] = obj.getAgriculturalTypeData();

//Model层

 public List<SelectListItem> getAgriculturalTypeData()
        {
            //创建新元素
            List<SelectListItem> P_Item = new List<SelectListItem>();

            //设置默认数据
            P_Item.Add(new SelectListItem() { Text = "请选择分类", Value = "0",Selected=true });

            //数据表数据筛选 并转化为list对象
            List<tablea> P_Table = EmpDB.tablea.OrderBy(OrderField => OrderField.Order).ToList();

            //数据循环
            foreach (var P_ItemData in P_Table.Where(StrWhere => StrWhere.Level == 0))
            {
                //数据元素填充
                P_Item.Add(new SelectListItem() { Text = P_ItemData.Name, Value = P_ItemData.ID.ToString() });

                //子类绑定
                List<SelectListItem> ChildList = getChildTypeList(P_ItemData.ID, P_Table);
              
                //循环
                foreach (var C_Item in ChildList)
                {                   
                    P_Item.Add(new SelectListItem() { Text = C_Item.Text, Value = C_Item.Value });
                }
            }
            return P_Item;
        }

 /// <summary>
        /// 递归绑定数据
        /// </summary>
        /// <param name="FID">父级ID</param>
        /// <param name="objtabList">数据表对象</param>
        public List<SelectListItem> getChildTypeList(Guid FID,List<tablea> objtabList)
        {
            //创建新元素
            List<SelectListItem>  C_Item=new List<SelectListItem>();

            //数据表数据筛选 并转化为list对象
            List<tablea> C_Table = objtabList.Where(StrWhere => StrWhere.FID == FID).OrderBy(OrderField => OrderField.Order).ToList();

            //数据循环
            foreach (var itemData in C_Table)
            {
                //数据元素填充
                C_Item.Add(new SelectListItem() { Text = itemData.Name, Value = itemData.ID.ToString() });

                //递归绑定
                C_Item.AddRange(getChildTypeList(itemData.ID, objtabList));
            }

            return C_Item;
        }