Easyui树菜单Tree(2)可拖拽修改层级,实时更新

图片.png

前台

<div id="divShipmentLayout" class="easyui-layout layout easyui-fluid" data-options="fit:true">
    <div id="divWest" data-options="region:'west',split:true" style="padding: 20px; width:25%; height: 100%;" title="" class="panel-body panel-body-noheader layout-body">
        <div class="easyui-panel" style="padding: 5px; width: 100%;">
            <ul class="easyui-tree" id="tt"></ul>
        </div>
    </div>
    <div id="divContainer" data-options="region:'center',split:true" style="padding: 20px; overflow-x: auto; width: 75%; height: 100%;" title="" class="panel-body panel-body-noheader layout-body">
        <div id="tb" class="divTable">
            <div class="divRow">
                <table id="tablestyle">
                    <tr>
                        <td><label style="text-align:right;">名称</label></td>
                        <td><input id="txtBusiness" class="easyui-textbox long textbox-f" style="width:200px;" data-options="required:true,validType:{length:[0,40]}" type="text" value="" textboxname="Business"></td>
                        <td><a id="toolbar_Create_table_TemplateList" onclick="addsever()">创建</a></td>
                        <td><a id="toolbar_Delete_table_TemplateList" onclick="delet()">删除</a></td>
                        <td><a id="toolbar_Update_table_TemplateList" onclick="upadtename()">更新</a></td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    //构造TreeJson数据
    function convert(rows) {
        function exists(rows, parentId) {
            for (var i = 0; i < rows.length; i++) {
                if (rows[i].id == parentId) return true;
            }
            return false;
        }
        var nodes = [];
        // get the top level nodes 一级
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            if (!exists(rows, row.parentId)) {
                nodes.push({
                    id: row.id,
                    text: row.name
                });
            }
        }
        var toDo = [];
        for (var i = 0; i < nodes.length; i++) {
            toDo.push(nodes[i]);
        }
        while (toDo.length) {
            var node = toDo.shift();    // the parent node
            // get the children nodes
            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];

                if (row.parentId == node.id) {
                    var child = { id: row.id, text: row.name };
                    if (node.children) {
                        node.children.push(child);
                    } else {
                        node.children = [child];
                    }
                    toDo.push(child);
                }
            }
        }
        return nodes;
    }

    $('#toolbar_Create_table_TemplateList').linkbutton({
        iconCls: 'icon-add'
    });
    $('#toolbar_Delete_table_TemplateList').linkbutton({
        iconCls: 'icon-clear'
    });
    $('#toolbar_Update_table_TemplateList').linkbutton({
        iconCls: 'icon-edit'
    });

    var jondatatree;
    //初始化加载树形
    $(function () {
       //$("#divContent").remove();
        $.ajax({
            type: "POST",
            url: window.location.protocol +"//"+ window.location.host+"@resourceHost/@ViewContext.RouteData.Values["Area"].ToString()/@ViewContext.RouteData.Values["Controller"].ToString()/GetTreedata",
            dataType: "json",
            success: function (data) {
                jondatatree = data.Table;
                funtree(data.Table);
            },
            error: function (jqXHR) {
                alert("发生错误:" + jqXHR.status);
            }
        });
        $('#divShipmentLayout').layout('resize', {
            height:  $(window).height() - 232
        });
    });

    //异步刷新
    var quert = function teer ()
    {
        UpperCored = [];
        targetCored = [];
        $.ajax({
            type: "POST",
            url: window.location.protocol + "//" + window.location.host + "@resourceHost/@ViewContext.RouteData.Values["Area"].ToString()/@ViewContext.RouteData.Values["Controller"].ToString()/GetTreedata",
            dataType: "json",
            success: function (data) {
                jondatatree = data.Table;
                funtree(data.Table);
                console.log("loadData");
            }
        })
    }

    //树菜单绑定
    var targetCored = Array();
    var deptid;
    function funtree(data) {
        $('#tt').tree({
            dnd: true,
            animate: true,
            lines: true,
            data: data,
            loadFilter: function (data) {
                return convert(data);
            },
            onClick: function (node) {
                //单击添加
                ThisCored(node.id, node.text);
                targetCored = [];
                targetCored.push(UpperCored[0]);
                //$("#tt").tree("loadData", []); 重新加载
                fixed_appears(node);
                $('#txtBusiness').textbox('setValue', node.text);
                deptid = parseInt(node.id + 1);
            },
            onDragOver: function (target, source) {
                var nodes = $('#tt').tree('getData', target);//更改后的上级节点 target:被放置的目标节点元素。
                ThisCored(nodes.id, nodes.text);
                targetCored = [];
                targetCored.push(UpperCored[0]);
                ThisCored(source.id, source.text);
                console.log(nodes);//上级节点
                console.log(source); //source:被拖拽的源节点
            },
            onDrop: function (node) {
                var nodes = $('#tt').tree('getData', node);
                deptid = parseInt(nodes.id + 1);
                upadte("dnd");
            }
        });
    }

    //点击获取cored 三级节点
    var UpperCored = Array();
    var Name_tex;
    function ThisCored(id, text) {
        debugger;
        treeid = id;
        UpperCored = [];
        for (var i = 0; i < jondatatree.length; i++) {
            var index = i;
            if (jondatatree[index].id == id) {
                id = jondatatree[index].parentId;
                Name_tex = text;
                IE_indexOf(jondatatree[index].Upper_Dept);
                if (treeid == id) {
                    if (UpperCored.indexOf(jondatatree[index].Upper_Dept) == -1) {
                        UpperCored.push(jondatatree[index].Upper_Dept);
                    }
                }
                else {
                    if (UpperCored.indexOf(jondatatree[index].DEPT_CODE) == -1) {
                        UpperCored.push(jondatatree[index].DEPT_CODE);
                    }
                }
                i = -1;
            }
        }
    }

    function IE_indexOf(code) {
        var a = new Array(UpperCored);
        //for ie can't support indexof
        if (!Array.indexOf) {
            Array.prototype.indexOf = function (obj) {
                for (var i = 0; i < this.length; i++) {
                    if (this[i] == obj) {
                        return i;
                    }
                }
                return -1;
            }
        }
        var index_id = a.indexOf(code);
    }

    //删除
    function delet() {
        if (!treeonClick()) {
            $.ajax({
                type: "POST",
                url: window.location.protocol + "//" + window.location.host + "@resourceHost/@ViewContext.RouteData.Values["Area"].ToString()/@ViewContext.RouteData.Values["Controller"].ToString()/DeltDepartmentAndValue/" + UpperCored[0],
                traditional: true,
                success: function (data) {
                    if (data) {
                        quert();
                    }
                },
                error: function () {

                }
            });
        }

    }

    function addsever() {
        if (!treeonClick()) {
            if ($("#txtBusiness").val().toString() == "" || nmetext == $("#txtBusiness").val().toString()) {
                $.messager.alert('@Label.Alert', '存在相同数据', 'warning');
                return;
            }
            var Cored = targetCored;
            var upper_cored;
            var jsondate = {};
            jsondate.Name = $("#txtBusiness").val().toString();
            if (Cored.length == 1) {
                upper_cored = getRanNum();
                jsondate.Dept_Code = upper_cored;
            }
            else {
                upper_cored = Cored.toString();
                jsondate.Dept_Code = upper_cored + '-' + getRanNum();
            }
            jsondate.Upper_Dept = targetCored.toString();
            jsondate.Line_ID = parseInt(deptid);
            var data = [jsondate];
            $.ajax({
                type: "POST",
                url: window.location.protocol + "//" + window.location.host + "@resourceHost/@ViewContext.RouteData.Values["Area"].ToString()/@ViewContext.RouteData.Values["Controller"].ToString()/AddDepartmentAndValue",
                traditional: true,
                dataType: "JSON",
                data: { jsonStr: JSON.stringify(data) },
                success: function (data) {
                    if (data) {
                        quert();
                    }
                }
            });
        }
    }

    //修改  manual 手动  dnd拖动
    function upadte(type) {
        if (!treeonClick()) {
            //当前节点关系 TheCurrent
            var CurrentCored = Array();
            for (var i = 0; i < UpperCored.length; i++) {
                if (i + 1 != UpperCored.length) {
                    CurrentCored.push(UpperCored[i])
                }
                else { break; }
            }
            //改动后节点关系
            var VauleCored = Array();
            if (type == "dnd") {
                VauleCored.push(targetCored);
                VauleCored.push(deptid);
            }
            if (CurrentCored.toString() == VauleCored.toString()) {
                return;
            } else {
                $.ajax({
                    type: "POST",
                    url: window.location.protocol + "//" + window.location.host + "@resourceHost/@ViewContext.RouteData.Values["Area"].ToString()/@ViewContext.RouteData.Values["Controller"].ToString()/UpdateDepartmentAndValue",
                    traditional: true,
                    dataType: "JSON",
                    data: { CurrentCode: CurrentCored.toString(), ChangetCode: VauleCored.toString() },
                    success: function (data) {
                        if (data) {
                            quert();
                        }
                    }
                });

            }
        }
    }

    //修改框
    var X, Y, Nme_Code,nmetext;
    function fixed_appears(node) {
        X = node.target.offsetLeft+65;
        Y = node.target.offsetTop+110;
        nmetext = node.text;
        for (var i = 0; i < jondatatree.length; i++) {
            if (parseInt(node.id) == parseInt(jondatatree[i].id)) {
                Nme_Code = jondatatree[i].DEPT_CODE.toString();
            }
        }
    }

    //修改名称
    function upadtename() {
        if (!treeonClick()) {
            if ($("#txtBusiness").val().toString() == "" || nmetext == $("#txtBusiness").val().toString()) {
                $.messager.alert('@Label.Alert', '未做更改', 'warning');
                return;
            }
            $.ajax({
                type: "POST",
                url: window.location.protocol + "//" + window.location.host + "@resourceHost/@ViewContext.RouteData.Values["Area"].ToString()/@ViewContext.RouteData.Values["Controller"].ToString()/Updatename/" + Nme_Code + "/" + $("#txtBusiness").val().toString(),
                traditional: true,
                success: function (data) {
                    if (data) {
                        quert();
                    }
                }
            });
        }
    }

    function treeonClick() {
        var stuet = false;
        if (typeof (jondatatree) != "undefined") {
            stuet = UpperCored.length > 0 && targetCored.length > 0 ? false : true;
            if (stuet) {
                $.messager.alert('@Label.Alert', '@Message.SelectOneToOperation', 'warning');
            }
        }
        return stuet;
    }

    //节点Cored 生成规则
    function getRanNum() {
        var result = [];
        for (var i = 0; i < 3; i++) {
            var ranNum = Math.ceil(Math.random() * 25);
            result.push(String.fromCharCode(65 + ranNum));
        }
        var num = RndNum(2);
        return result.join('') + num;
    }

    function RndNum(n) {
        var rnd = "";
        for (var i = 0; i < n; i++)
            rnd += Math.floor(Math.random() * 10);
        return rnd;
    }

</script>
<style type="text/css">
    td {
        padding-right: 10px;
    }
</style>

后台Controllers:

using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using iROCK.Resource;
using iROCK.Foundation.Web;
using iROCK.Entity.Framework;
using iROCK.Interface.Framework;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;
using System.IO;
using Newtonsoft.Json.Linq;

namespace iROCK.Web.Areas.Framework.Controllers
{
    [Route(WebConst.ROUTE_TEMPLATE_WITH_AREA)]
    [Area(Const.WEB_AREA_FRAMEWORK)]

    public class DepartmentController : WebController
    {
        IDepartmentService m_DepartmentService;
        public DepartmentController(IDepartmentService departmentService, ILoggerFactory loggerFactory) : base(loggerFactory)
        {
            m_DepartmentService = departmentService;
        }

        //json序列化 用接收前台参数
        public class jsondata
        {
            public string Name { get; set; }               //名称
            public string Dept_Code { get; set; }      //当前 编码 Code    
            public string Upper_Dept { get; set; }     //上级编码  Code
            public int? Line_ID { get; set; }               //id
        }

        [HttpPost()]
        [HttpGet()]
        public JsonResult GetDepartments()
        {
            var Departments = m_DepartmentService.GetDepartments(Facility, Site, Language);
            return Json(Departments);
        }


        [HttpPost()]
        [HttpGet()]
        public JsonResult GetGroupName()
        {
            var Departments = m_DepartmentService.GetGroupName(Facility, Site, Language);
            return Json(Departments);
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost()]
        [HttpGet()]
        public string GetTreedata()
        {
            var Departments = m_DepartmentService.GetTreedata(Configuration["ConnectionStrings:DefaultConnection"], Facility, Site, Language);
            return Departments;//Json(Departments);
        }

        [HttpPost()]
        [HttpGet()]
        public bool AddDepartmentAndValue()
        {
            //获取前台json
            string jsondata = Request.Form["jsonStr"];
            var JsonArray = JArray.Parse(jsondata);
            var listArray = JsonArray.ToObject<List<jsondata>>();
            List<object> addlist = listArray.ConvertAll(s => (object)s);
            var Departments = m_DepartmentService.AddDepartmentAndValue(new Department(), addlist, UserID, Facility, Site);
            return Departments;
        }

        [HttpPost("{Dept_Code}")]
        [HttpGet("{Dept_Code}")]
        public bool DeltDepartmentAndValue(string Dept_Code)
        {
            var Departments = m_DepartmentService.DeltDepartmentAndValue(new Department(), Dept_Code, UserID, Facility, Site);
            return Departments;
        }


        [HttpPost()]
        [HttpGet()]
        public bool UpdateDepartmentAndValue()
        {
            //被拖拽的源节点
            string Currentjson = Request.Form["CurrentCode"];
            List<object> CurrentCode = new List<object>(Currentjson.Split(','));

            //目标节点 
            string Changetjson = Request.Form["ChangetCode"];
            List<object> ChangetCode = new List<object>(Changetjson.Split(','));
            var Departments = m_DepartmentService.UpdateDepartmentAndValue(new Department(), CurrentCode, ChangetCode, UserID, Facility, Site);
            return Departments;
        }

        [HttpPost("{Nme_Code}/{txtName}")]
        [HttpGet("{Nme_Code}/{txtName}")]
        public bool Updatename(string Nme_Code,string txtName)
        {
            var Departments = m_DepartmentService.Updatename(new Department(), Nme_Code, txtName, UserID, Facility, Site);
            return Departments;
        }

        public JsonResult GetBusinessType()
        {
            var Departments = m_DepartmentService.GetBusinessType(Facility, Site, Language);
            return Json(Departments);
        }
    }
}

接口实现层 Interface.Implementation

public static string GetTreedata(this IRepository<Department> departmentRepository, string connectString, string facility, string site, string language)
{
    //树形菜单绑定
    string str = $@"
    IF NOT OBJECT_ID(N'Tempdb..#T2') IS NULL
        DROP TABLE #T2;
    SELECT  R.id, DE.DEPT_CODE ,
            VA.MEANING AS name ,
            DE.UPPER_DEPT,
            R1.parentId,
            LINE_ID,
            ISNULL(DE.MODIFY_DATE,ISNULL(VA.MODIFY_DATE,ISNULL(R.MODIFY_DATE,ISNULL(R1.MODIFY_DATE,DE.CREATE_DATE)))) AS UP_DATE
    INTO #T2
    FROM    SY_S_DEPARTMENT DE
            INNER JOIN SY_S_GLOBAL_MULTIPLE_LANGUAGE_VALUE VA ON DE.DEPT_CODE = VA.LOOKUP_VALUE
            INNER JOIN ( SELECT ROW_NUMBER() OVER ( ORDER BY CREATE_DATE,DEPT_CODE ASC ) AS id ,
                                DEPT_CODE,MODIFY_DATE
                            FROM   SY_S_DEPARTMENT
                        ) AS R ON R.DEPT_CODE = DE.DEPT_CODE 
            LEFT JOIN ( SELECT ROW_NUMBER() OVER ( ORDER BY CREATE_DATE,DEPT_CODE ASC ) AS ParentId ,
                                DEPT_CODE,MODIFY_DATE
                            FROM   SY_S_DEPARTMENT
                        ) AS R1 ON R1.DEPT_CODE = DE.UPPER_DEPT
    WHERE   VA.LANGUAGE = '{language}' --'zh-cn'
            AND DE.FACILITY='{facility}'
            AND DE.SITE='{site}'; 
    WITH    menu ( id, name, DEPT_CODE, UPPER_DEPT, parentId,LINE_ID,UP_DATE, Level, px, px2 )
                AS ( SELECT   id ,
                            name ,
                            DEPT_CODE ,
                            UPPER_DEPT ,
                            parentId ,
                            LINE_ID,
                            UP_DATE,
                            0 AS Level ,
                            id px ,
                            CAST(id AS NVARCHAR(4000)) px2
                    FROM     #T2
                    WHERE    parentId IS NULL
                    UNION ALL
                    SELECT   A.id ,
                            A.name ,
                            A.DEPT_CODE ,
                            A.UPPER_DEPT ,
                            A.parentId ,
                            A.LINE_ID,
                            A.UP_DATE,
                            B.Level + 1 ,
                            B.px ,
                            B.px2 + LTRIM(A.id)
                    FROM     #T2 A
                            INNER JOIN menu B ON A.parentId = B.id
                    )
        SELECT  id ,
                name ,
                DEPT_CODE ,
                UPPER_DEPT ,
                CASE WHEN parentId IS NULL AND DEPT_CODE='DO' AND id=1 THEN 0
                        WHEN parentId IS NULL AND DEPT_CODE <>'DO'AND id<>1 THEN 1
                        ELSE parentId
                END AS parentId ,
                LINE_ID,
                Level ,
                px ,
                px2
        FROM    menu
        ORDER BY LINE_ID ASC,UP_DATE DESC;";
    DataSet ds = departmentRepository.ExecuteDataSet(connectString, str.ToString(), null);
    //转json
    string jsondata = string.Empty;
    if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
    {
        var json = ToDictionary(ds);//ToDictionaryList(ds.Tables[0]);
        jsondata = JsonConvert.SerializeObject(json);
    }
    return jsondata;
}

其它就只是增删查改

©著作权归作者所有,转载或内容合作请联系作者
禁止转载,如需转载请通过简信或评论联系作者。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,132评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,802评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,566评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,858评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,867评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,695评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,064评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,705评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,915评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,677评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,796评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,432评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,041评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,992评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,223评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,185评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,535评论 2 343

推荐阅读更多精彩内容