前台
<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;
}
其它就只是增删查改