双树 节点 C# net Ztree linqtosql 源码

架构设计 模块架构

 结果 操作左边的树异步刷新右边的树


从中需要用到

 JS 

ajax 

ztree  

js调用C#后台方法 

递归 

JS回调函数

linqtosql

C#基础知识


注意事项  :文章的ztree使用的标准对象模式 

使用ztree时 有两种方式   都对数据库的设计有很大的要求 

主要要有ID 和 ParentID

使用简单对象模式时 需要注意还要加一个ISparent 字段 判断是否为节点

一下是使用标准对象模式的源码 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MS.DAL.DBML;
using MS.DAL.LINQ_DAL.Common;

namespace MS.Web.MS_Styseting.MS_Organize
{
    public class Company_childrenweb 
    {
        private List<Company_childrenweb> _children;

        public List<Company_childrenweb> children
        {
            get { return _children; }
            set { _children = value; }
        }

        private string _cId;

        public string cId
        {
            get { return _cId; }
            set { _cId = value; }
        }
        private string _cName;

        public string cName
        {
            get { return _cName; }
            set { _cName = value; }
        }

        private string _cParentId;

        public string cParentId
        {
            get { return _cParentId; }
            set { _cParentId = value; }
        }
        private string _cUrl;
        public string cUrl
        {
            get { return _cUrl; }
            set { _cUrl = value; }
        }

        private string _cParentrightID;
        public string cParentrightID
        {
            get { return _cParentrightID; }
            set { _cParentrightID = value; }
        }
    }
}




后台

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using MainloserTree.DAL;

namespace MainloserTree.Sys
{
    public partial class MailLoserZtreeView : System.Web.UI.Page
    {
        private static string connectionString = ConfigurationManager.ConnectionStrings["Maillosertree"].ToString();//连接数据库的


        public string Sys_Organizeid = "97fb8de4-56e7-457b-856d-388ba91ea5e0";
        public int Cid = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
            }
        }

        //XML里面的一个方法,在jquery用ajax方法调用;  ok01
        /// <summary>  
        /// 获取所有的一级节点  
        /// </summary>  
        /// <returns>所有的节点信息</returns>  
        [WebMethod]
        public static List<Sys_Organize> FindAll()
        {
            //实例化类  
            MailLoserZtreeView mS_OrganZtreeJ = new MailLoserZtreeView();
            string sqlText = "select * from Sys_Organize where ParentID=0";
            //定义实体类列表  
            List<Sys_Organize> list = new List<Sys_Organize>();
            //将所有的一级节点放到list中  
            list = mS_OrganZtreeJ.GetParentID(sqlText);
            // mS_OrganZtreeJ.GetChilds(ref list);  
            return list;
        }



        //XML里面的一个方法,在jquery用ajax方法调用;  OK0201
        /// <summary>  
        /// 获取所有的一级节点   Q群196997099
        /// </summary>  
        /// <returns>所有的节点信息</returns>  
        /// 
        [WebMethod]
        public static List<Company_childrenweb> FindAllCompanyK(string Sys_Organizeid)
        {
            //实例化类 string Sys_Organizeid
            if (Sys_Organizeid == null)
            {
                Sys_Organizeid = "97fb8de4-56e7-457b-856d-388ba91ea5e0";
            }
            MailLoserZtreeView mS_OrganZtreeJ = new MailLoserZtreeView();
            //表连接   Q群196997099
           string sqlText =
                String.Format(@"select * from dbo.Company c join Sys_Organize s on c.Organizeid=s.ID where s.ID='{0}'",
                              Sys_Organizeid);
            //定义实体类列表  
            List<Company_childrenweb> listCompany = new List<Company_childrenweb>();
            //将所有的一级节点放到list中  
            listCompany = mS_OrganZtreeJ.GetCompanyParentID(sqlText); // OK0202
            mS_OrganZtreeJ.GetChildslistCompany(ref listCompany); // OK0204  
            return listCompany;
        }

        /// <summary>  
        ///获所有的一级节点  
        /// </summary>  
        /// <param name="sql"></param>  
        /// <returns></returns>  
        public List<Sys_Organize> GetParentID(string sql)
        {
            List<Sys_Organize> user = new List<Sys_Organize>();
            SqlDataReader reader = null;
            reader = ExecuteReader(sql);
            while (reader.Read())
            {
                user.Add(ObjToListC(reader));
            }
            return user;
        }


        /// <summary>  
        ///获所有的一级节点  ok0202
        /// </summary>  
        /// <param name="sql"></param>  
        /// <returns></returns>  
        private List<Company_childrenweb> GetCompanyParentID(string sql)
        {
            List<Company_childrenweb> user = new List<Company_childrenweb>();
            SqlDataReader reader = null;
            reader = ExecuteReader(sql);
            while (reader.Read())
            {
                user.Add(ObjToListKCompany(reader)); //ok0203
            }
            return user;
        }

        /// <summary>  
        /// 将获取的所有的子节点放到children中  
        /// </summary>  
        /// <param name="list">按引用传值,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中</param>  
        public void GetChilds(ref List<Sys_Organize> list)
        {

            foreach (Sys_Organize modelChilds in list)
            {

                //通过上级ID获取子级,然后添加到lstModel中  
                List<Sys_Organize> lstModel = GetChildsID(modelChilds.ID);
                if (lstModel.Count > 0)
                {
                    modelChilds.ID = lstModel[0].ID;
                    modelChilds.ParentID = lstModel[0].ParentID;
                    modelChilds.Remark = lstModel[0].Remark;
                    modelChilds.OrganizeCode = lstModel[0].OrganizeCode;
                    modelChilds.OrganizeName = lstModel[0].OrganizeName;
                    //  modelChilds.children = lstModel;  
                    //  model.;osmf = lstModel;
                    //采用递归的形式  
                    GetChilds(ref lstModel);
                }
            }
        }

        /// <summary>  
        /// 将获取的所有的子节点放到children中  ok0204
        /// </summary>  
        /// <param name="list">按引用传值,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中</param>  
        public void GetChildslistCompany(ref List<Company_childrenweb> list)
        {
            
            foreach (Company_childrenweb modelChilds in list)
            {
                //通过上级ID获取子级,然后添加到lstModel中  Q群196997099
                List<Company_childrenweb> lstModelCompany = GetChildsIDCompany(modelChilds.cId);
                if (lstModelCompany.Count > 0)
                {
                    modelChilds.children = lstModelCompany;  //这个就是树的关键难点 这个决定了与夫节点的关系 加一个list到对象里去
                    //采用递归的形式   
                    GetChildslistCompany(ref lstModelCompany);
                }
            }
        }

        /// <summary>  
        /// 根据父节点的id获取子节点  
        /// </summary>  
        /// <param name="dParentId">父节点id</param>  
        /// <returns>所有的子节点id</returns>  
        public List<Company_childrenweb> GetChildsIDCompany(string dParentId)
        {
            //定义一个列  
            List<Company_childrenweb> result = new List<Company_childrenweb>();
            SqlDataReader sqlReader = null;
            //  var  ObjToListCCompanybbb;
            string strSql = String.Format(@"select * from Company where ParentrightID='{0}'", dParentId);
            sqlReader = ExecuteReader(strSql);
            while (sqlReader.Read())
            {
                result.Add(ObjToListKCompany(sqlReader));
            }
            sqlReader.Close();
            return result;
        }

        /// <summary>  
        /// 根据父节点的id获取子节点  
        /// </summary>  
        /// <param name="dParentId">父节点id</param>  
        /// <returns>所有的子节点id</returns>  
        public List<Sys_Organize> GetChildsID(string dParentId)
        {
            //定义一个列  
            List<Sys_Organize> result = new List<Sys_Organize>();
            SqlDataReader sqlReader = null;
            string strSql = String.Format(@"select * from Sys_Organize where ID='{0}'", dParentId);
            sqlReader = ExecuteReader(strSql);
            while (sqlReader.Read())
            {
                result.Add(ObjToListC(sqlReader));
            }
            sqlReader.Close();
            return result;
        }

        /// <summary>  
        /// 解析查询结果  
        /// </summary>  
        /// <param name="reader"></param>  
        /// <returns>父节点id,子节点id,子节点名字</returns>  
        private Sys_Organize ObjToListC(SqlDataReader reader)
        {
            Sys_Organize model = new Sys_Organize();
            if (reader != null)
            {
                //子节点id  
                if (reader["ParentID"] != null && reader["ParentID"].ToString() != "")
                {
                    model.ParentID = int.Parse(
                        reader["parentID"].ToString()
                        )
                        ;
                }
                //节点名字  
                if (reader["OrganizeName"] != null && reader["OrganizeName"].ToString() != "")
                {
                    model.OrganizeName = reader["OrganizeName"].ToString();
                }
                //父节点id  
                if (reader["ParentID"] != null && reader["ParentID"].ToString() != "")
                {
                    model.ParentID = int.Parse(
                        reader["ParentID"].ToString()
                        );
                }
                //地址  
                if (reader["Remark"] != null && reader["Remark"].ToString() != "")
                {
                    model.Remark = reader["Remark"].ToString();
                }

                //code 
                if (reader["OrganizeCode"] != null && reader["OrganizeCode"].ToString() != "")
                {
                    model.OrganizeCode = reader["OrganizeCode"].ToString();
                }

                //节点名字  
                if (reader["ID"] != null && reader["ID"].ToString() != "")
                {
                    model.ID = reader["ID"].ToString();
                }
                //节点名字  
                if (reader["Sort"] != null && reader["Sort"].ToString() != "")
                {
                    model.Sort = int.Parse(
                        reader["Sort"].ToString());
                }

            }
            return model;
        }



        /// <summary>  
        /// 解析查询结果  
        /// </summary>  
        /// <param name="reader"></param>  
        /// <returns>父节点id,子节点id,子节点名字</returns>  
        private Company_childrenweb ObjToListKCompany(SqlDataReader reader)
        {
            Company_childrenweb model = new Company_childrenweb();
            if (reader != null)
            {
                //子节点id  
                if (reader["ID"] != null && reader["ID"].ToString() != "")
                {
                    model.cId = reader["ID"].ToString();
                    //  model.ID = int.Parse(reader["ID"].ToString());
                }
                //节点名字  
                if (reader["CompanyName"] != null && reader["CompanyName"].ToString() != "")
                {
                    model.cName = reader["CompanyName"].ToString();
                }
                //父节点id  
                if (reader["ParentrightID"] != null && reader["ParentrightID"].ToString() != "")
                {
                    model.cParentId = reader["ParentrightID"].ToString();
                }
                //id  
                if (reader["Organizeid"] != null && reader["Organizeid"].ToString() != "")
                {
                    model.cUrl = reader["Organizeid"].ToString();
                }

            }
            return model;
        }

        /// <summary>  
        /// 解析查询结果  
        /// </summary>  
        /// <param name="reader"></param>  
        /// <returns>父节点id,子节点id,子节点名字</returns>  
        private static Company ObjToListCCompany(SqlDataReader reader)
        {
            Company model = new Company();
            if (reader != null)
            {
                //子节点id  
                if (reader["ID"] != null && reader["ID"].ToString() != "")
                {
                    model.ID = int.Parse(reader["ID"].ToString());
                }
                //节点名字  
                if (reader["CompanyName"] != null && reader["CompanyName"].ToString() != "")
                {
                    model.CompanyName = reader["CompanyName"].ToString();
                }
                //父节点id  
                if (reader["Levelid"] != null && reader["Levelid"].ToString() != "")
                {
                    model.Levelid = int.Parse(reader["Levelid"].ToString());
                }
                //id  
                if (reader["categoryid"] != null && reader["categoryid"].ToString() != "")
                {
                    model.categoryid = reader["categoryid"].ToString();
                }

                //code 
                if (reader["companytype"] != null && reader["companytype"].ToString() != "")
                {
                    model.companytype = reader["companytype"].ToString();
                }

                //节点名字  
                if (reader["Organizeid"] != null && reader["Organizeid"].ToString() != "")
                {
                    model.Organizeid = reader["Organizeid"].ToString();
                }
                //节点名字  
                if (reader["CompanyID"] != null && reader["CompanyID"].ToString() != "")
                {
                    model.CompanyID = reader["CompanyID"].ToString();
                }
                //节点名字  
                if (reader["ParentrightID"] != null && reader["ParentrightID"].ToString() != "")
                {
                    model.ParentrightID = int.Parse(reader["ParentrightID"].ToString());
                }
            }
            return model;
        }


        private static SqlDataReader ExecuteReader(string strSQL)
        {
            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand(strSQL, connection);
            try
            {
                connection.Open();
                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return myReader;
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                throw e;
            }
        }
    }
}




前台

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MailLoserZtreeView.aspx.cs" Inherits="MainloserTree.Sys.MailLoserZtreeView" %>

<!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 id="Head1" runat="server">
    <title>MS_OrganZtreeJ</title>
    <link href="../Scripts/JS/zTree_v3/css/zTreeStyle/zTreeStyle.css" rel="stylesheet"
        type="text/css" />
     <link href="../Scripts/JS/zTree_v3/css/zTreeStyle/zTreeStyle.css" rel="stylesheet" type="text/css" />
    <script src="../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="../Scripts/JS/zTree_v3/js/jquery.ztree.core-3.5.js" type="text/javascript"></script>
    <script src="../Scripts/JS/Json2.js" type="text/javascript"></script>
 <script type="text/javascript">

     var Organizeidjs5 = "635afc02-c57d-4356-aa75-c825d691a6d7";
   
     function showIconForTree(treeId, treeNode) {
         return !treeNode.isParent;
     };

     function zTreeOnClick(event, treeId, treeNode) {
         alert(treeNode.tId + ", " + treeNode.name + "," + treeNode.id);
         //获取地址  
         var url = treeNode.cUrl;
         //打开链接  
         // open(url);  
         //用于框架中  
         open(url, "_parent", true);
     }


     function zTreeOnClickleftztree(event, treeId, treeNode) {
         alert(treeNode.tId + ", " + treeNode.name + "," + treeNode.id + "," + treeId + "," + treeNode.OrganizeName + "," + treeNode.ParentID + "," + treeNode.ID);
         Organizeidjs5 = treeNode.ID;
         $.ajax({
             type: "post",
             contentType: "application/json",
             url: "MailLoserZtreeView.aspx/FindAllCompanyK",
             data: "{'Sys_Organizeid':'" + Organizeidjs5 + "'}",
             dataType: "json",
             error: function () {//请求失败处理函数  
                 alert('请求失败');
             },
             beforeSend: function () {
                 Organizeidjs5 = treeNode.ID;
             },
             success: function (data2) {
                 var treeNodes2 = new Object();
                 treeNodes2 = data2.d;
                 $.fn.zTree.init($("#treeDemo2"), setting2, treeNodes2);
             }
         });

     }

     //显示右键菜单  
     function showRMenu(type, x, y) {
         $("#rMenu ul").show();
         if (type == "root") {
             $("#m_del").hide();
             $("#m_check").hide();
             $("#m_unCheck").hide();
         }
         $("#rMenu").css({ "top": y + "px", "left": x + "px", "display": "block" });
     }
     //隐藏右键菜单  
     function hideRMenu() {
         $("#rMenu").hide();
     }

     //鼠标右键事件- 
     function zTreeOnRightClick(event, treeId, treeNode) {
         if (!treeNode) {
             zTree.cancelSelectedNode();
             showRMenu("root", event.clientX, event.clientY);
         } else if (treeNode && !treeNode.noR) { //noR属性为true表示禁止右键菜单  
             if (treeNode.newrole && event.target.tagName != "a" && $(event.target).parents("a").length == 0) {
                 zTree.cancelSelectedNode();
                 showRMenu("root", event.clientX, event.clientY);
             } else {
                 zTree.selectNode(treeNode);
                 showRMenu("node", event.clientX, event.clientY);
             }
         }
     }
     var setting = {

         callback: {
             onClick: zTreeOnClickleftztree, //回调函这个触发点击左边树控制右边
             rightClick: zTreeOnRightClick   //右键事件待完善  
         },
         view: {
             showIcon: showIconForTree
         },
         data: {
             key: {
                 ID: "ID",
                 children: "nodes",
                 name: "OrganizeName",
                 title: "OrganizeName",
                 OrganizeCode: "OrganizeCode"
                 // url: "Remark"  
             },
             simpleData: {
                 enable: false
             }
         }
     };

     var setting2 = {
         callback: {
             onClick: zTreeOnClick
         },     
         view: {
             //  isParent: true,
             showIcon: showIconForTree
         },
         data: {

             key: {
                 children: "children",
                 name: "cName",
                 title: "",
                 url: "URL"
             },
             simpleData: {
                 enable: true
             }
         }
     };

     $(document).ready(function () {

         hideRMenu();
         $.ajax({
             type: "post",
             contentType: "application/json",
             url: "MailLoserZtreeView.aspx/FindAll",
             data: "{}",
             dataType: "json",
             error: function () {//请求失败处理函数  
                 alert('请求失败');
             },
             success: function (data) {
                 var treeNodes = data.d; //接受webservice里面传过来的list  
                 $.fn.zTree.init($("#treeDemo"), setting, treeNodes);
             }
         });
         $.ajax({
             type: "post",
             contentType: "application/json",
             url: "MailLoserZtreeView.aspx/FindAllCompanyK",
             data: "{'Sys_Organizeid':'" + Organizeidjs5 + "'}",
             dataType: "json",
             //success: function (result) {  
             error: function () {//请求失败处理函数  
                 alert('请求失败');
             },
             success: function (data2) {
                 var treeNodes2 = data2.d;   //接受webservice里面传过来的list  
                 // treeNodes2 = JSON.stringify(treeNodes2); //这是 js转json
                 //创建ztree  
                 $.fn.zTree.init($("#treeDemo2"), setting2, treeNodes2);
             }


         });


     });


 </script>  
</head>  
<body>
  
  
    <form id="form1" runat="server">
       <table> <tr>
                <td> <div>  
        <ul id="treeDemo" class="ztree">  
        </ul>  
    </div>  
    </td>
     <td> 
    <div>  
        <ul id="treeDemo2" class="ztree">  
        </ul>  
    </div>  
    </td> 
            </tr>  
            </table>
  

    </form>  
   
    
</body>


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页