• C#无限分级实现,前端WEB页面接收,后台提供层级Json数据


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Text;
    using System.Data;
    using System.Collections;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using RBAC;
    using Newtonsoft.Json;
    
    public partial class DepartmentConfig : BaseRolePage
    {
        protected DataTable dtTree = new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                dtTree = Maticsoft.DBUtility.DbHelperSQL.Query("select * from SY_DEPARTMENT").Tables[0];
            }
        }
    
        #region 获取无限分级数据
        /// <summary>
        /// 获取无限分级数据
        /// </summary>
        /// <returns></returns>
        protected string GetLevelJson()
        {
            //获取全部集合
            List<DepartModel> allModel = new List<DepartModel>();
            DataTable dt = dtTree.Copy();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                DepartModel model = new DepartModel();
                model.id = (int)dr["departID"];
                model.dname = dr["departName"].ToString();
                model.fid = (int)dr["fatherDepartID"];
                allModel.Add(model);
            }
            //筛选顶级分类
            var topItems = allModel.Where(e => e.fid == 0).ToList(); //顶级分类
            List<DepartModel> topModels = new List<DepartModel>();
            foreach (var item in topItems)
            {
                DepartModel topModel = new DepartModel();
                topModel.id = item.id;
                topModel.dname = item.dname;
                topModel.fid = item.fid;
                LoopToAppendChildren(allModel, topModel);
                topModels.Add(topModel);
            }
    
            string json = JsonConvert.SerializeObject(topModels);
            return json;
        }
    
        /// <summary>
        /// 继续追溯子类
        /// </summary>
        /// <param name="allList">全部数据</param>
        /// <param name="curItem">当前节点</param>
        protected void LoopToAppendChildren(List<DepartModel> allList, DepartModel curItem)
        {
            var subItems = allList.Where(ee => ee.fid == curItem.id).ToList();
            curItem.childs = new List<DepartModel>();
            curItem.childs.AddRange(subItems);
            foreach (var subItem in subItems)
            {
                LoopToAppendChildren(allList, subItem);
            }
        }
        #endregion
    
        #region 数据实体类
        public class DepartModel
        {
            public int id;
            public string dname;
            public int fid;
            public List<DepartModel> childs;
        }
        #endregion
    }
    

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="DepartmentConfig.aspx.cs" Inherits="DepartmentConfig" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>组织架构</title>
        <link type="text/css" rel="stylesheet" href="../css/default.css" />
        <link type="text/css" rel="stylesheet" href="../css/jquery_dialog.css" />
        <link rel="stylesheet" type="text/css" href="../JS/jquery-easyui-1.5/themes/default/easyui.css" />
        <script type="text/javascript" src="../JS/jquery-easyui-1.5/jquery.min.js"></script>
        <script type="text/javascript" src="../JS/jquery_dialog.js"></script>
        <script type="text/javascript" src="../js/common.js"></script>
        <script type="text/javascript">
            $(function(){
                var json=<%=GetLevelJson()%>;
                var tableHtml= "<table id='tableAction' class='tableCss'>";
                tableHtml += "<th>部门ID</th><th>部门名称</th><th></th>";
                tableHtml +="</table>";
                $(".LoopSpan").empty().append(tableHtml); 
                $.each(json, function (index) {  
                    //循环获取数据 顶级   
                    var id = json[index].id;  
                    var name = json[index].dname;  
                    var fatherid = json[index].fid; 
                    var childs = json[index].childs; 
                    //组装
                    DoLoop("",childs,name,id,fatherid,0);
                });
                //注册删除事件
                $(".alink_del").click(function(){
                    if (confirm("确定删除?")) {
                        var id = $(this).attr("data-id");
                        $.ajax({
                            url: 'RoleHandler.ashx',
                            data: { "method": "delete_depart", "id": id },
                            type: 'GET',
                            timeout: 1000,
                            cache: false,
                            error: erryFunction,   
                            success: succFunction  
                        })
                        function erryFunction() {
                            alert("error");
                        }
                        function succFunction(data) {
                            //0无参数 1有下级 2删除成功 3删除失败
                            switch (data) {
                                case "0":
                                    alert("参数错误");
                                    break;
                                case "1":
                                    alert("此数据存在下级,为防止误操作
    确保数据安全,请从末级往上逐级删除。");
                                    break;
                                case "2":
                                    alert("删除成功!");
                                    window.location.href = window.location.href;
                                    break;
                                case "3":
                                    alert("删除失败,请稍后再试!");
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                });
    
                //折叠展开
                $(".tree-hit").click(function(){
                    var data=[];
                    var children = [];
                    $("#tableAction").find("tr").each(function(i){
                        var id=$(this).attr("data-id");
                        var fid=$(this).attr("data-fid");
                        if (typeof(id)!="undefined") {
                            data.push({"id":id, "fid":fid});
                        }                    
                    });               
                    var id=$(this).parent().parent().attr("data-id");
                    if (typeof(id)!="undefined") {
                        //是否折叠
                        var closeFlag= $(this).hasClass("tree-expanded") ? true:false; 
                        var arr=getChildren(data,children,id);
                        if (closeFlag) { //折叠
                            $(this).removeClass("tree-expanded").addClass("tree-collapsed");
                            //tree-folder tree-folder-open           //tree-folder 
                            $(this).next("span").removeClass("tree-folder-open")
                        }
                        else{ //展开
                            $(this).removeClass("tree-collapsed").addClass("tree-expanded");
                            $(this).next("span").addClass("tree-folder-open")                  
                        }
                        openClose(arr,closeFlag);
    
                    };
                });
            });
    
            //递归获取子类及下属类 无限下级
            function getChildren(data,children,id)
            {
                for(var i=0;i<data.length;i++){
                    var iid=data[i]["id"];
                    var fid=data[i]["fid"];
                    if(id == fid){
                        children.push(iid);
                        getChildren(data,children,iid);      
                    }
                }
                return children;
            }
    
            //折叠展开
            function openClose(arr,closeFlag)
            {
                $("#tableAction").find("tr").each(function(i){
                    var id=$(this).attr("data-id");   
                    if($.inArray(id,arr)>-1){
                        if (closeFlag) { //折叠
                            $(this).find("span").eq(0).removeClass("tree-collapsed").addClass("tree-expanded");
                            $(this).find("span").eq(1).addClass("tree-folder-open")  
                            $(this).hide();
                        }
                        else{ //展开
                            $(this).find("span").eq(0).removeClass("tree-collapsed").addClass("tree-expanded");
                            $(this).find("span").eq(1).next("span").addClass("tree-folder-open")     
                            $(this).show();
                        }                    
                    }                
                });
            }
            
            //递归            
            function DoLoop(loopHtml,child_models,dname,id,fatherid,level)
            {
                var loopHtml = "";
                loopHtml += "<tr data-id='" + id + "' data-fid='" + fatherid + "'>";
                loopHtml += "<td width='10%' style='text-align:center'>";
                loopHtml += id;
                loopHtml += "</td>";
                loopHtml += "<td valign='bottom' width='40%' style='text-align:left'>"
                loopHtml += PreText(level) ;
                //<span class="tree-hit tree-collapsed"></span>
                loopHtml += (child_models.length > 0) ? "<span id='" + id + "' class="tree-hit tree-expanded"></span><span class="tree-icon tree-folder tree-folder-open"></span>":"<span class="tree-icon tree-file"></span>"; //tree-open
                loopHtml += dname;
                loopHtml += "</td>";
                loopHtml +="<td width='50%'>";      
                loopHtml +="<a href='javascript:showMyModalDialog("DepartmentAdd.aspx?fid=" + id + "","600","300");'>新增下级</a>    ";
                loopHtml +="<a href='javascript:showMyModalDialog("DepartmentEdit.aspx?id=" + id + "","600","300");'>编辑</a>    ";
                loopHtml +="<a href='javascript:void(0);' data-id='" + id + "' class='alink_del'>删除</a>";
                loopHtml +="</td>"; 
                loopHtml +="</tr>";
                $("#tableAction").append(loopHtml);
                
                if (child_models.length > 0) { //有子类
                    level++;
                    $.each(child_models, function (index) {
                        var id = child_models[index].id;  
                        var name = child_models[index].dname;  
                        var fatherid = child_models[index].fid; 
                        var childs = child_models[index].childs; 
                        //递归
                        DoLoop(loopHtml,childs,name,id,fatherid,level);
                    });
                }           
            }
    
            function PreText(level)
            {
                var str="";
                for (var i = 0; i < level; i++) {
                    str +="      ";
                }
                str += (level>0) ? " " :"";
                return str;
            }
        </script>
        <style type="text/css">
            tree-open {
                background: url('images/tree_icons.png') no-repeat -96px 0px;
            }
    
            tree-close {
                background: url('images/tree_icons.png') no-repeat -112px 0px;
            }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
            <span class="tableTip">组织架构</span>
            <div class="LoopSpan"></div>
            <br />
            <table class="tableCss">
                <tr>
                    <td></td>
                </tr>
            </table>
        </form>
    </body>
    </html>
    

    [
        {
            "id": 600,
            "dname": "集团中国总部",
            "fid": 0,
            "childs": [
                {
                    "id": 601,
                    "dname": "广东省公司",
                    "fid": 600,
                    "childs": [
                        {
                            "id": 602,
                            "dname": "深圳分公司",
                            "fid": 601,
                            "childs": [
                                {
                                    "id": 603,
                                    "dname": "福田办事处",
                                    "fid": 602,
                                    "childs": [
                                        {
                                            "id": 613,
                                            "dname": "车公庙办事点",
                                            "fid": 603,
                                            "childs": []
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                },
                {
                    "id": 606,
                    "dname": "湖南省公司",
                    "fid": 600,
                    "childs": [
                        {
                            "id": 607,
                            "dname": "长沙分公司",
                            "fid": 606,
                            "childs": []
                        }
                    ]
                },
                {
                    "id": 612,
                    "dname": "上海市公司",
                    "fid": 600,
                    "childs": []
                }
            ]
        },
        {
            "id": 604,
            "dname": "集团美国总部",
            "fid": 0,
            "childs": [
                {
                    "id": 605,
                    "dname": "纽约分公司",
                    "fid": 604,
                    "childs": [
                        {
                            "id": 611,
                            "dname": "曼哈顿办事处",
                            "fid": 605,
                            "childs": []
                        }
                    ]
                }
            ]
        }
    ]

  • 相关阅读:
    你还在钟情于windows XP吗?
    我常用的vim快捷键
    2013年读的书(很多还没看完)
    期末考试了
    顺着自己的心,去做自己喜欢的事
    关于最近新闻泛滥的几点看法以及学习的个人观点
    华为OJ_1
    【Android】弹出软键盘时候让上面布局跟着上移的方法
    【Android】策略模式封装百度地图路线规划模块
    google觉得好用的插件(不断更新)
  • 原文地址:https://www.cnblogs.com/smartsmile/p/6234051.html
Copyright © 2020-2023  润新知