树型控件拖拽排序
上次分享了“一个可以拖拽的异步按需加载树”,但没有实现拖拽后更新数据库,今天抽空把他实现了,这里分享下思路及关键代码。
拖拽方法入口:
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 ,欢迎大家把玩。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述