树型控件拖拽排序

上次分享了“一个可以拖拽的异步按需加载树”,但没有实现拖拽后更新数据库,今天抽空把他实现了,这里分享下思路及关键代码。

拖拽方法入口:

        function onDrop(event, treeId, treeNodes, targetNode, moveType, isCopy) {
            if (targetNode != null) {
                $.post("/Ashx/FileType.ashx?action=DragSortNum", { treeNodesId: treeNodes[0].id, targetNodeId: targetNode.id }, function (txt) {
                    if (txt != "OK") {
                        alert("更新排序号失败,请稍后再试!");
                    }
                }, "text");
            }
        }

这里只需要传两个参数到后台即可,分别是当前拖拽节点ID及拖拽目标ID,拖拽又分为往上拖拽和往下拖拽,这里对数据库里更新的排序号有不同的算法。

详细代码如下:

        public Boolean UpdateFileTypeSortNum(String treeNodeId, String targetNodeId)
        {
            using (SqlConnection conn = DapperFactory.CrateOpenConnection())
            {
                //判断节点是往上移还是往下移
                var treeNode = GetFileType(new Guid(treeNodeId));
                var targetNode = GetFileType(new Guid(targetNodeId));

                if (treeNode.SortNum <= targetNode.SortNum)
                {
                    //往下移
                    String executeSql = String.Format(@" UPDATE FileType SET SortNum = SortNum+2
                                    WHERE ID in(SELECT A.ID from [FileType] A,FileType B 
                                                where B.ID='{0}'
                                                and A.ParentId=B.ParentId and A.SortNum >= B.SortNum) ", targetNodeId);
                    conn.Execute(executeSql, null);

                    executeSql = String.Format(@"update t1 set t1.SortNum=t2.SortNum+1
                                from FileType t1,FileType t2 
                                where t1.ID='{0}' and t2.ID='{1}'", treeNodeId, targetNodeId);
                    conn.Execute(executeSql, null);
                }
                else
                {
                    //往上移
                    String executeSql = String.Format(@" UPDATE FileType SET SortNum = SortNum+1
                                    WHERE ID in(SELECT A.ID from [FileType] A,FileType B 
                                                where B.ID='{0}'
                                                and A.ParentId=B.ParentId and B.SortNum <= A.SortNum) ", targetNodeId);
                    conn.Execute(executeSql, null);

                    executeSql = String.Format(@"update t1 set t1.SortNum=t2.SortNum-1
                                from FileType t1,FileType t2 
                                where t1.ID='{0}' and t2.ID='{1}'", treeNodeId, targetNodeId);
                    conn.Execute(executeSql, null);
                }
                return true;
            }
        }

至此,大功搞成,如果觉得不错,请点击推荐,谢谢。

如有不足,请多提宝贵意见。

Demo网址:http://www.qicheba.net/FileManage/TypeManage ,欢迎大家把玩。

版权声明:程序员胖胖胖虎阿 发表于 2023年9月3日 下午5:40。
转载请注明:树型控件拖拽排序 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...