zl程序教程

您现在的位置是:首页 >  前端

当前栏目

JQuery/JS插件 jsTree加载树,普通加载,点一级加载一级

jQueryJS插件 加载 普通 一级
2023-09-11 14:22:27 时间

 

 

前端:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <div id="plugins1"></div>


    <link href="../jstree/themes/default/style.min.css" rel="stylesheet" />
    <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.js"></script>
    <script src="../jstree/jstree.min.js"></script>




    <script type="text/javascript">


        //Checkbox plugin
        $(function () {
            $("#plugins1").jstree({
                "checkbox": {
                    //"keep_selected_style": true//显示选中的样式
                    //"keep_selected_style": false,// 保持选中样式 true为保持,false为不保存,样式不影响功能
                    'three_state': true,//父子节点关联,true为关联,false为不关联
                    'tie_selection': false, //
                    'whole_node': false,//复选框与节点关联 true 为关联 false为不关联
                },
                "plugins": ["checkbox"],//加载插件 checkbox
                'core': {
                    'expand_selected_onload': true,//加载完成后默认展开所有选中节点true为选中 false为不展开
                    'themes': {
                        dots: true //取消连接线
                    },
                    'data': {
                        'url': function (node) {
                            return './Handler3.ashx';
                        },
                        'data': function (node) {
                            return { 'id': node.id };
                        }
                    }
                }
            });


        });

    </script>
</body>
</html>
View Code

 

 

后端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;

namespace WebApplication1.jstree测试
{
    /// <summary>
    /// Handler3 的摘要说明
    /// </summary>
    public class Handler3 : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json; charset=utf-8";

            object obj = null;

            var id = context.Request["id"].ToString();
            if (id == "#")
            {
                obj = GetRoot();
            }
            else
            {
                obj = GetChildren(int.Parse(id));
            }

            //var list = GetProjectTrees();
            string strContent = JsonConvert.SerializeObject(obj);
            context.Response.Write(strContent);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }




        public List<ProjectOutPut> GetRoot()
        {
            var dt = ExecuteDataTable($"select * from Projects7 where [ParentId]=0 order by Id asc", null);
            var allProject = DataTableToEntities<Projects>(dt);
            var first = allProject.Where(p => p.ParentId == 0).First();
            return new List<ProjectOutPut> { new ProjectOutPut {
                id = first.Id,
                    text = first.ProjectName,
                    ParentId = first.ParentId,
                    children = true
            } };
        }



        public List<ProjectOutPut> GetChildren(int Pid)
        {
            var dt = ExecuteDataTable($"select * from Projects7 where [ParentId]={Pid} order by Id asc", null);
            if (dt.Rows.Count <= 0)
            {
                return new List<ProjectOutPut>();
            }

            var allProject = DataTableToEntities<Projects>(dt);
            var list = new List<ProjectOutPut>();
            allProject.ForEach(c =>
            {
                list.Add(new ProjectOutPut
                {
                    id = c.Id,
                    text = c.ProjectName,
                    ParentId = c.ParentId,
                    children = true
                });
            });
            return list;
        }


        

        /// <summary>
        /// 返回值以所以为object类型,是因为jstree的“+”号
        /// object实际只有两种类型 bool 和 list
        /// </summary>
        /// <param name="project"></param>
        /// <param name="all"></param>
        /// <param name="showAddSign">jstree是否显示“+”号</param>
        /// <returns></returns>
        public object GetChildrenProject(Projects project, IReadOnlyList<Projects> all, bool showAddSign = true)
        {
            var outputModel = new List<ProjectOutPut>();

            if (all.Count(p => p.ParentId == project.Id) > 0)
            {
                var children = all.Where(p => p.ParentId == project.Id).ToList();

                foreach (var childProject in children)
                {
                    outputModel.Add(new ProjectOutPut()
                    {
                        id = childProject.Id,
                        text = childProject.ProjectName,
                        ParentId = childProject.ParentId,
                        children = GetChildrenProject(childProject, all, showAddSign)
                    });
                }
            }
            if (showAddSign && (outputModel.Count == 0))
            {
                return true;
            }
            return outputModel;
        }








        //dto
        public class ProjectOutPut
        {
            public int id { get; set; }
            public string text { get; set; }
            public int? ParentId { get; set; }

            public object children { get; set; }
        }

        //实体类
        public class Projects
        {
            public int Id { get; set; }
            public string ProjectName { get; set; }
            public int? ParentId { get; set; }
            public int IsEnabled { get; set; }
            public int TaskStatus { get; set; }

            public string ProjectCode { get; set; }
            public int? ProjectOrder { get; set; }
        }




        // 返回DataTable
        public static DataTable ExecuteDataTable(string sql, params SqlParameter[] param)
        {
            string conStr = "data source=.\\sqlexpress;initial catalog=TEST1;user id=sa;password=sa;";

            DataTable dt = new DataTable();

            using (SqlConnection con = new SqlConnection(conStr))
            {
                using (SqlDataAdapter adapter = new SqlDataAdapter(sql, con))
                {
                    //添加参数
                    if (param != null)
                    {
                        adapter.SelectCommand.Parameters.AddRange(param);
                    }
                    //1.打开链接,如果连接没有打开,则它给你打开;如果打开,就算了
                    //2.去执行sql语句,读取数据库
                    //3.sqlDataReader,把读取到的数据填充到内存表中
                    adapter.Fill(dt);
                }
            }
            return dt;
        }

        // DataTable转换为Entitys
        public static List<T> DataTableToEntities<T>(DataTable dt) where T : class, new()
        {
            if (null == dt || dt.Rows.Count == 0) { return null; }
            List<T> entities = new List<T>();
            List<string> columnNames = new List<string>();

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                columnNames.Add(dt.Columns[i].ColumnName);
            }

            foreach (DataRow row in dt.Rows)
            {
                PropertyInfo[] pArray = typeof(T).GetProperties();
                T entity = new T();

                Array.ForEach<PropertyInfo>(pArray, p =>
                {
                    if (!columnNames.Contains(p.Name))
                    {
                        return;
                    }

                    object cellvalue = row[p.Name];

                    //空值不处理
                    if (cellvalue == DBNull.Value)
                    {
                        return;
                    }
                    if ((cellvalue == null) || string.IsNullOrWhiteSpace(cellvalue.ToString().Trim()))
                    {
                        return;
                    }

                    if (cellvalue != DBNull.Value)
                    {
                        //经过了几个版本的迭代,最后一个为最新的,摘自网上,已附原文地址

                        //4、原地址:https://blog.csdn.net/Simon1003/article/details/80839744
                        if (!p.PropertyType.IsGenericType)
                        {
                            p.SetValue(entity, Convert.ChangeType(cellvalue, p.PropertyType), null);
                        }
                        else
                        {
                            Type genericTypeDefinition = p.PropertyType.GetGenericTypeDefinition();
                            if (genericTypeDefinition == typeof(Nullable<>))
                            {
                                p.SetValue(entity, Convert.ChangeType(cellvalue, Nullable.GetUnderlyingType(p.PropertyType)), null);
                            }
                            else
                            {
                                throw new Exception("genericTypeDefinition != typeof(Nullable<>)");
                            }
                        }
                    }
                });
                entities.Add(entity);
            }
            return entities;
        }



    }
}
View Code

 

数据:

数据和上一篇的一样的