Fork me on GitHub
.net求学者

添加树形菜单Easyui

Asp.net添加Easyui Tree树简单快捷方法--匿名对象转Json

     /// <summary>
        /// 获取树
        /// </summary>
        private void GetExamineDicTree()
        {
            string strJson = "[]";
            var listData = new T_ExamineDicDAL().GetAll();
            if (listData != null && listData.Count > 0)
            {
                strJson = JsonHelper.GetUnknownJson(GetChildren("KH", listData));//KH为顶级根节点ID(Null),并转换为Json格式
            }
            Response.Write(strJson);
            Response.End();
        }
        /// <summary>
        /// 获取子节点数据--递归
        /// </summary>
        /// <param name="strUpDicID"></param>
        /// <param name="listData"></param>
        /// <returns></returns>
        private List<dynamic> GetChildren(string strUpDicID, List<T_ExamineDicInfo> listData)
        {
            List<dynamic> listDy = new List<dynamic>();
            var tempList = listData.Where(f => f.UpDicID == strUpDicID);
            if (tempList != null)
            {
                foreach (var item in tempList)
                {var model = new
                    {
                        id = item.DicID,
                        text = item.DicName,
                        state = "open",
                        //attributes:{tip:'',states:false}
                        children = GetChildren(item.DicID, listData)
                    };

                    listDy.Add(model);
                }
            }
            return listDy;
        }
$.ajax({
    type: 'POST',
    url: location.href,
    data: { "action": "getTree" },
    dataType: 'json',
    success: function (treeData) {
        $('#ExamineDicTree').tree({
            data: treeData,
            checkbox: true,
            //url:''
        });
    }
});

 

方案一:

 #region 树节点
    /// <summary>
    /// 加载树信息
    /// </summary>
    public void LoadTree()
    {
        TreeView1.Nodes.Clear();
        DataTable dtbt = BD.GetDataTable("", 0);
        foreach (DataRow row in dtbt.Rows)
        {
            if (row["ParentDept"].ToString() == "-1")
            {
                TreeNode tn = new TreeNode();
                tn.Text = row["DeptName"].ToString();
                tn.Value = row["ID"].ToString();
                tn.ToolTip = row["Type"].ToString();
                tn.ImageUrl = "~/images/list_zxxx.gif";
                //tn.NavigateUrl = "javascript:SelectedNodeChanged('" + row["ID"] + "')";
                TreeView1.Nodes.Add(tn);
            }
        }
        foreach (TreeNode tn in TreeView1.Nodes)
        {
            CallMeTree(tn, dtbt.Select(), dtbt);
        }
        TreeView1.ExpandAll();
    }
    /// <summary>
    /// 递归调用
    /// </summary>
    /// <param name="node">当前节点</param>
    /// <param name="Rows"></param>
    /// <param name="dt"></param>
    public void CallMeTree(TreeNode node, DataRow[] Rows, DataTable dt)
    {
        foreach (DataRow row in Rows)
        {
            if (row["ParentDept"].ToString() == node.Value)
            {
                TreeNode tn = new TreeNode();
                
                tn.Value = row["ID"].ToString();
                tn.ToolTip = row["Type"].ToString();
                if (tn.ToolTip == "岗位")
                {
                    tn.Text = row["DeptName"].ToString() + "-人数:" + row["UserCount"].ToString();
                    tn.ImageUrl = "~/images/list_dbsy.gif";
                }
                else
                {
                    tn.Text = row["DeptName"].ToString();
                    tn.ImageUrl = "~/images/folder.gif";
                }
                //tn.NavigateUrl = "javascript:SelectedNodeChanged('" + row["ID"] + "')";
                node.ChildNodes.Add(tn);
                DataRow[] _rows = dt.Select(string.Format(" ParentDept = {0} ", tn.Value));
                if (_rows.Length > 0)
                {
                    CallMeTree(tn, _rows, dt);
                }
            }
        }
    }

    //选中节点
    public void SelNode(string id, TreeNodeCollection nodes)
    { 
        foreach (TreeNode n in nodes)
        {
            if (n.Value == id)
            {
                n.Select();
                this.TreeView1.SelectedNodeStyle.ForeColor = System.Drawing.Color.Red;
                return;
            }
            if (n.ChildNodes.Count > 0)
                SelNode(id, n.ChildNodes);
        }
    }


    /// <summary>
    /// 展开二级
    /// </summary>
    public void ExpandLevel()
    {
        //只展开2级菜单
        foreach (TreeNode node1 in TreeView1.Nodes)
            foreach (TreeNode node2 in node1.ChildNodes)
                node2.Collapse();
    }

    protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
    {
        TreeNode node = TreeView1.SelectedNode;
        string _id = TreeView1.SelectedValue;
        //执行其他操作
    }
    #endregion

 

 

方案二:

 /// <summary>
    /// 菜单
    /// </summary>
    void getMen()
    {
        DataSet ds = hrSystem.DAL.oaOpt.oa.P_Sys_MenuListGetList();
        DataTable dt = ds.Tables[0];
        DataTable CurrDt = dt;
        string TreeHtml = "";
        foreach (DataRow dr in CurrDt.Select())
        {
            if (dr["ParentMenuID"] == DBNull.Value)
            {
                //ProcList.Contains(dr["MenuID"].ToString().Trim()) 这样也可以但是数据库要规划
                if (ProcList.Split(',').Contains(dr["MenuID"].ToString().Trim()) || ProcList == "-1")
                {
                    string MenuID = dr["MenuID"].ToString();
                    string MenuName = dr["MenuName"].ToString();
                    string TreeHtmlOut = foreachTree(MenuID, MenuName, dt);
                    TreeHtml += TreeHtmlOut;
                }
            }
        }
        tree = TreeHtml;
    }

    //递归遍历
    public string foreachTree(string MenuID, string MenuName, DataTable dt)
    {
        string ChildTreeHtml = "";
        ChildTreeHtml += @" <li><span class='modules' id='" + MenuID + "'>" + MenuName + "</span><ul>";
        if (dt.Select("ParentMenuID='" + MenuID + "'").Count() > 0)
        {
            foreach (DataRow drinfo in dt.Select("ParentMenuID='" + MenuID + "'"))
            {
                if (ProcList.Split(',').Contains(drinfo["MenuID"].ToString().Trim()) || ProcList == "-1")
                {
                    string CurrNO = drinfo["MenuID"].ToString();
                    string CurrName = drinfo["MenuName"].ToString();
                    string TreeHtmlOut = foreachTree(CurrNO, CurrName, dt);
                    ChildTreeHtml += TreeHtmlOut;
                }
            }
        }
        else
        {
            DataRow[] Childr = dt.Select("MenuID='" + MenuID + "'");
            string chilName = Childr[0]["MenuName"].ToString();
            string ramd = new Random().NextDouble().ToString();
            string chilLi = @"<li><span class='func' id='" + MenuID + "' datatype='iframe'  datalink='" + Childr[0]["ProLink"] + "?" + ramd + "'  iconimg='images/skype.png'>" + chilName + "</span></li>";
            return chilLi;
        }
        ChildTreeHtml += "</ul></li>";
        return ChildTreeHtml;
    }
   Response.Write(tree);
        Response.End();
<div class="divMain">
        <div class="divLeft">
            <ul id="menulists" class="functree">
            </ul>
        </div>
        <div class="divRight">
        </div>
    </div>


<script type="text/javascript">
    function loadmenu() {
        $.ajax({
            url: 'OaFrom.aspx?e=' + new Date().getTime(),
            type: 'GET',

            success: function (msg) {
                if (msg == "-1") {
                    if (parent == window) {
                        parent.location.href = "login.html?" + new Date().getTime();
                    }
                    else {
                        location.href = "login.html?" + new Date().getTime();
                    }

                }
                $("#menulists").html(msg);
                loaddefault();
            }
        })
    }

 var jericho = {
        showLoader: function () {
            $('#divMainLoader').css('display', 'block');
        },
        removeLoader: function () {
            $('#divMainLoader').css('display', 'none');
        },
        buildTree: function () {
            $('.functree li').each(function () {
                if ($(this).is(':has(ul)'))
                    $(this).addClass('collapse');
                if ($(this).next().is('li') || $(this).next().is('ul'))
                    $(this).css({ borderLeft: 'dashed 1px #dedede' });
            })
            $('li.collapse>span').on('click', function () {
                $(this).next('ul').slideToggle('fast', function () {
                    if ($(this).parent().hasClass('collapse'))
                        $(this).parent().removeClass('collapse').addClass('expand');
                    else
                        $(this).parent().removeClass('expand').addClass('collapse');
                })
            })

            $('span.func').css({ 'cursor': 'pointer' }).hover(function () {
                $(this).css({ 'color': '#3de', 'text-decoration': 'underline' });
            }, function () {
                $(this).css({ 'color': '#000', 'text-decoration': 'none' });
            }).click(function () {
                $.fn.jerichoTab.addTab({
                    tabFirer: $(this),
                    title: $(this).text(),
                    closeable: true,
                    iconImg: $(this).attr('iconImg'),
                    data: {
                        dataType: $(this).attr('dataType'),
                        dataLink: $(this).attr('dataLink')
                    }
                }).showLoader().loadData();
            });
        },
        buildTabpanel: function () {
            $.fn.initJerichoTab({
                renderTo: '.divRight',
                uniqueId: 'myJerichoTab',
                contentCss: { 'height': $('.divRight').height() - 50 },
                tabs: [{
                    title: '运行状态',
                    closeable: false,
                    iconImg: 'images/jerichotab.png',
                    data: { dataType: 'iframe', dataLink: '/ManagementSys/502.htm' },
                    onLoadCompleted: function (h) {
                        $('<b style="color:red" />').html('欢迎进入后台管理系统').appendTo(h);
                    }
                }],
                activeTabIndex: 0,
                loadOnce: true
            });
        }
    }

    function loaddefault() {
        d1 = new Date().getTime();
        jericho.showLoader();
        var w = $(window).width();
        var h = $(window).height();
        $('.divLeft').css({ width: 190, height: h - 60, 'display': 'block' });
        $('.divRight').css({ width: w - 226, height: h - 60, 'display': 'block' });
        jericho.buildTree();
        jericho.buildTabpanel();
        jericho.removeLoader();
    }

    $(function () {
        loadmenu();
    })
    $(window).resize(function () {
        //$('.divRight').animate({ width: 226 },500);
        setTimeout(function () {
            var w = $(window).width();
            var h = $(window).height();

            $('.divLeft').animate({ height: h - 60 }, 500)
            $('.divRight').animate({ width: w - 226, height: h - 60 }, 500);
        }, 1);
    }) 
</script>

 

posted @ 2014-03-03 15:52  hy31337  阅读(548)  评论(0编辑  收藏  举报
.net求学者