MVC+EF 实现树结构 设备分组增删改查

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u012154630/article/details/79637336

一、界面效果:


二、代码

1.DeviceGrouping.js

//页面初始加载方法
window.onload = function () {
    $("#addDeviceGroupDialog").dialog("close");

    readDevices();
    readDevicesGroup();
    ztreeload();
    ztreeGroupload();

    zTreeObj = $.fn.zTree.init($("#devicetree"), setting, nodes);
    zTreeGroup = $.fn.zTree.init($("#GroupName"), gsetting, Groupnodes);
    //清空设备名称检索
    $('#clearText').click(function () {
        $('#deviceName').val("");
    });
    //添加设备分组弹框关闭X
    $('.about-close').click(function () {
        $("#addDeviceGroupDialog").dialog("close");
    });
}

//$(function () {
//    winHeight = $(window).height(); //获取电脑屏幕的高
//    $("#GroupName").css({ height: winHeight - 235 });
//    $("#devicetree").css({ height: winHeight - 235 });


//});

var nodes = [];
var Groupnodes = [];
var distancedata = null;
var Groupdata = null;
var zTreeObj;
var zTreeGroup;
var code;
var devicedata = null;
function setFontCss(treeId, node) {
    return { 'color': node.devicecolor };
}

var gsetting = {
    async: {
        enable: false //开启异步加载处理
    },
    view: {
        expandSpeed: "", //zTree 节点展开、折叠时的动画速度,设置方法同 JQuery 动画效果中 speed 参数。
        //addHoverDom: addHoverDom, //用于当鼠标移动到节点上时,显示用户自定义控件,显示隐藏状态同 zTree 内部的编辑、删除按钮
        removeHoverDom: removeHoverDom, //用于鼠标移出节点时,隐藏自定义用户
        selectedMulti: false, // 禁止多点同时选中的功能 
        fontCss: { color: "black" }
    },
    edit: {
        enable: true, //设置 zTree 进入编辑状态
        removeTitle: "删除",
        renameTitle: "编辑",
        editNameSelectAll: true,
        showRemoveBtn: showRemoveBtn,
        showRenameBtn: showRenameBtn

    },
    data: {
        simpleData: {
            enable: true, //使用简单 Array 格式的数据
            idKey: "id",
            pIdKey: "pId"
        },
        keep: {
            parent: true
        }
    },
    callback: {
        beforeDrag: beforeDrag,
        beforeRemove: beforeRemove,
        beforeRename: beforeRename,
        onRemove: onRemove,
        onRename: onRename

    },
    check: {
        chkdisabledInherit: false,
        enable: true,
        chkStyle: "radio"
    }
};



function showRenameBtn(treeId, treeNode) {
    if (treeNode.pId == null) {
        return false;
    }
    else if (treeNode.pId != 1) {
        return false;
    }
    else {
        return true;
    }
}
function showRemoveBtn(treeId, treeNode) {
    if (treeNode.pId == null) {
        return false;
    }
    else {
        return true;
    }
}
function getTime() {
    var now = new Date(),
			h = now.getHours(),
			m = now.getMinutes(),
			s = now.getSeconds(),
			ms = now.getMilliseconds();
    return (h + ":" + m + ":" + s + " " + ms);
}
function beforeDrag(treeId, treeNodes) {
    return false;
}
var treeNodeId = "";
var log, className = "dark";
function beforeEditName(treeId, treeNode) {
    className = (className === "dark" ? "" : "dark");
    showLog("[ " + getTime() + " beforeEditName ]     " + treeNode.name);
    var zTree = $.fn.zTree.getZTreeObj("GroupName");
    zTree.selectNode(treeNode);
    return confirm("进入节点 -- " + treeNode.name + " 的编辑状态吗?");
}
function beforeRemove(treeId, treeNode) {
    className = (className === "dark" ? "" : "dark");
    showLog("[ " + getTime() + " beforeRemove ]     " + treeNode.name);
    var zTree = $.fn.zTree.getZTreeObj("GroupName");
    zTree.selectNode(treeNode);
    if (confirm("确认删除 节点 -- " + treeNode.name + " 吗?")) {
        if (treeNodeId != "")
            treeNodeId += ",";
        treeNodeId += treeNode.id;
        deleteDeviceGroup(treeNode);
        return true;
    }
    else {
        return false;
    }
}
function onRemove(e, treeId, treeNode) {
    showLog("[ " + getTime() + " onRemove ]     " + treeNode.name);
}
function beforeRename(treeId, treeNode, newName, isCancel) {
    if (treeNode.name == newName) {
        return true;
    }
    if (!ISexistence(newName)) {
        return false;
    }
    else {
        className = (className === "dark" ? "" : "dark");
        showLog((isCancel ? "<span style='color:red'>" : "") + "[ " + getTime() + " beforeRename ]     " + treeNode.name + (isCancel ? "</span>" : ""));
        if (newName.length == 0) {
            alert("节点名称不能为空.");
            var zTree = $.fn.zTree.getZTreeObj("GroupName");
            setTimeout(function () { zTree.editName(treeNode) }, 10);
            return false;
        }
        else {
            var PId = treeNode.id;
            if (typeof PId == "string") {
                PId = PId.replace("P", "");
            }
            $.ajax({
                url: "/InstantPatrol/EditDevicegroup",
                type: "post",
                data: { PId: PId, name: newName },
                datatype: "json",
                asnyc: false,
                success: function (data) {
                    if (data) {
                        alert("操作成功!");
                    } else {
                        alert("操作失败!");
                    }
                }
            });
        }
    }
}


function onRename(e, treeId, treeNode, isCancel) {
    showLog((isCancel ? "<span style='color:red'>" : "") + "[ " + getTime() + " onRename ]     " + treeNode.name + (isCancel ? "</span>" : ""));
}

function showLog(str) {
    if (!log) log = $("#log");
    log.append("<li class='" + className + "'>" + str + "</li>");
    if (log.children("li").length > 8) {
        log.get(0).removeChild(log.children("li")[0]);
    }
}

//ZTee设置
var setting = {
    view: {
        fontCss: setFontCss
    },
    check: {
        enable: true,
        autoCheckTrigger: true,
        chkboxType: { "Y": "s", "N": "s" }
    },
    callback: {
        onCheck: onCheck
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pId",
            rootPId: 0

        }
    }

};

//读取设备信息Instant
function readDevices() {
    $.ajax({
        url: '/InstantPatrol/GetDevicesInfoTree',
        type: 'post',
        datatype: 'json',
        async: false,
        success: function (_data) {
            devicedata = _data;
        },
        error: function () { }
    });
}

//读取设备信息
function readDevicesGroup() {
    $.ajax({
        url: '/InstantPatrol/GetzTree',
        type: 'post',
        datatype: 'json',
        async: false,
        success: function (_data) {
            Groupdata = _data;
        },
        error: function () { }
    });
}

//初始化ZTree
function ztreeload() {
    nodes = [];
    var Devicename = $("#deviceName").val().toUpperCase();
    var n = { id: 1, pId: 0, name: "移动巡更设备", open: true, nocheck: true, iconOpen: "../../../scripts/js/plugins/zTree-v3/css/zTreeStyle/img/diy/1_open.png", iconClose: "../../../scripts/js/plugins/zTree-v3/css/zTreeStyle/img/diy/1_close.png" };
    nodes.push(n);
    if (Devicename != "") {
        for (var i = 0; i < devicedata.length; i++) {
            if (devicedata[i].device_name.toUpperCase().indexOf(Devicename) > -1 && devicedata[i].group_id == -1) {
                n = { id: devicedata[i].Id, pId: 1, name: devicedata[i].device_name, isParent: false, icon: "../../../scripts/js/plugins/zTree-v3/css/zTreeStyle/img/diy/zzman.png", deviceid: devicedata[i].id, deviceguid: devicedata[i].DeviceGUID, devicetype: devicedata[i].device_type, devicex: devicedata[i].local_x, devicey: devicedata[i].local_y, longitude: devicedata[i].Longitude, latitude: devicedata[i].Latitude, devicecolor: devicedata[i].route_color };
                nodes.push(n);
            }

        }
    }
    else {
        for (var i = 0; i < devicedata.length; i++) {
            if (devicedata[i].group_id == -1) {
                n = { id: devicedata[i].Id, pId: 1, name: devicedata[i].device_name, icon: "../../../scripts/js/plugins/zTree-v3/css/zTreeStyle/img/diy/zzman.png", deviceid: devicedata[i].id, deviceguid: devicedata[i].DeviceGUID, devicetype: devicedata[i].device_type, devicex: devicedata[i].local_x, devicey: devicedata[i].local_y, longitude: devicedata[i].Longitude, latitude: devicedata[i].Latitude, devicecolor: devicedata[i].route_color };
                nodes.push(n);
            }
        }
    }
    zTreeObj = $.fn.zTree.init($("#devicetree"), setting, nodes);
}


//Ztree勾选事件
function onCheck(event, treeId, treeNode) {
    var treeObj = $.fn.zTree.getZTreeObj("devicetree");
    var nodes = treeObj.getCheckedNodes(true);
}


//初始化ZTree
function ztreeGroupload() {
    Groupnodes = [];
    var n = { id: 1, pId: 0, name: "移动巡更分组列表", open: true, nocheck: true, iconOpen: "../../../scripts/js/plugins/zTree-v3/css/zTreeStyle/img/diy/1_open.png", iconClose: "../../../scripts/js/plugins/zTree-v3/css/zTreeStyle/img/diy/1_close.png", icon: "../../../scripts/js/plugins/zTree-v3/css/zTreeStyle/img/diy/1_open.png" };
    Groupnodes.push(n);
    for (var i = 0; i < Groupdata.length; i++) {
        if (Groupdata[i].pid == "") {
            n = { id: Groupdata[i].id, pId: 1, name: Groupdata[i].name, icon: "../../../scripts/js/plugins/zTree-v3/css/zTreeStyle/img/diy/zzman.png" };
            Groupnodes.push(n);
        }
        else {
            n = { id: Groupdata[i].id, pId: Groupdata[i].pid, name: Groupdata[i].name, icon: "../../../scripts/js/plugins/zTree-v3/css/zTreeStyle/img/diy/zzman.png", nocheck: true };
            Groupnodes.push(n);
        }
    }
    zTreeGroup = $.fn.zTree.init($("#GroupName"), gsetting, Groupnodes);

}
var newCount = 1;
function addHoverDom(treeId, treeNode) {
    var sObj = $("#" + treeNode.tId + "_span");
    if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
    var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
				+ "' title='add node' οnfοcus='this.blur();'></span>";
    sObj.after(addStr);
    var btn = $("#addBtn_" + treeNode.tId);
    if (btn) btn.bind("click", function () {
        var zTree = $.fn.zTree.getZTreeObj("GroupName");
        zTree.addNodes(treeNode, { id: (100 + newCount), pId: treeNode.id, name: "new node" + (newCount++) });
        return false;
    });
};
function removeHoverDom(treeId, treeNode) {
    $("#addBtn_" + treeNode.tId).unbind().remove();
};
function selectAll() {
    var zTree = $.fn.zTree.getZTreeObj("GroupName");
    zTree.setting.edit.editNameSelectAll = $("#selectAll").attr("checked");
}

//设备移动到设备分组
function deviceMoveGroup(groupid, deviceid) {
    $.ajax({
        url: '/InstantPatrol/deviceMoveGroup',
        type: 'post',
        data: { "groupid": groupid, "deviceid": deviceid },
        datatype: 'json',
        async: false,
        success: function (_data) {
            devicedata = _data;

            readDevices();
            readDevicesGroup();
            ztreeload();
            ztreeGroupload();
            alert("操作成功!");

        },
        error: function () {
            alert("操作失败!");
        }
    });
}



function addDeviceGroup() {

    var treeObj = $.fn.zTree.getZTreeObj("GroupName");
    Groupnodes = treeObj.getCheckedNodes(true);
    if (Groupnodes.length > 0) {
        var groupid = Groupnodes[0].id.substring(1);
    }
    else {
        alert("请选择分组");
        return;
    }

    var zTreeObj = $.fn.zTree.getZTreeObj("devicetree");
    nodes = zTreeObj.getCheckedNodes(true);
    var deviceid = ""
    if (nodes.length != 0) {
        if (nodes.length > 1) {
            for (var i = 0; i < nodes.length; i++) {
                deviceid += nodes[i].id + ",";
            }
        }
        else {
            deviceid = nodes[0].id;
        }
        if (Groupnodes.length == 0) {
            // poPupBox(); 
        }
        else {
            var children = getchildren();
            var newNode = children;
            var Subnode = ISSubnode(newNode);
            if (Subnode == true) {
                newNode = treeObj.addNodes(Groupnodes[0], newNode);
            }
            else {
                return false
            }
            //adddDeviceGroup(Groupnodes[0].name,existence)
            deviceMoveGroup(groupid, deviceid);
        }
    }
    else {
        alert("请选择要分组的设备");
        return;
    }

}

//判断节点存在否
function ISSubnode(newNode) {
    var se = true;
    var myArray = new Array();
    var treeObj = $.fn.zTree.getZTreeObj("GroupName");
    if (treeObj.getCheckedNodes(true)[0].isParent == true) {
        var nodes = treeObj.getCheckedNodes(true)[0].children;
        for (var i = 0; i < nodes.length; i++) {
            myArray.push(nodes[i].name);
        }
        for (var a = 0; a < newNode.length; a++) {
            if (myArray.indexOf(newNode[a].name) > -1) {
                alert("节点" + name + "已存在,请选择!");
                se = false;

                break;
            }
        }
    }
    return se;

}




//判断根节点存在否
function ISexistence(name) {
    var myArray = new Array();
    var treeObj = $.fn.zTree.getZTreeObj("GroupName");

    if (treeObj.getNodes()[0].isParent == true) {
        var nodes = treeObj.getNodes()[0].children;
        for (var i = 0; i < nodes.length; i++) {
            myArray.push(nodes[i].name);
        }
        if (myArray.indexOf(name) > -1) {
            alert("节点" + name + "已存在,请重新输入!");
            $("#groupname").focus();
            return false;
        }
    }
    return true;
}







function getchildren() {
    var sname = "";
    var CId = -1;
    var treeObj = $.fn.zTree.getZTreeObj("devicetree");
    nodes = treeObj.getCheckedNodes(true);
    var Childrenname = new Array();
    for (var i = 0; i < nodes.length; i++) {
        sname = nodes[i].name;
        CId = nodes[i].deviceid;
        var Children;
        Children = { id: CId, name: sname, open: false, nocheck: true, icon: "../../../scripts/js/plugins/zTree-v3/css/zTreeStyle/img/diy/zzman.png" };
        Childrenname.push(Children);
    }
    return Childrenname
}




var existence = false;
function poPupBox() {
    var a = dialog({
        id: 'AdddeviceGroup',
        title: '添加设备分组',
        left: 0,
        top: 0,
        fixed: true,
        content: "<p style=''><label>分组名称:</label><input type='text' class='form-control' id='Groupname'></p>",
        okValue: '提交',
        ok: function () {
            var name = $("#Groupname").val();
            var grouptype = 1//移动设备
            //            var children = getchildren()
            //            var treeObj = $.fn.zTree.getZTreeObj("GroupName");
            //            var newNodes = { name: name, icon: "../../../Scripts/js/zTree-v3/css/zTreeStyle/img/diy/zzman.png", pId: 1 };
            existence = ISexistence(name);
            if (existence == true) {
                adddDeviceGroup(name, existence)
            }
            else {
                return false;
            }

        },
        cancelValue: '取消',
        cancel: function () {

        }
    });
    a.show();
    $("#AdddeviceGroup").css({ "left": "70%", "top": "30%" });

}


function adddDeviceGroup(name, existence) {
    ///, grouptype: grouptype 
    var grouptype = 1;
    $.ajax({
        url: "/InstantPatrol/AddGroupInfo",
        type: "post",
        //data: { region_id: Number(RegionId), name: name, nodes: JSON.stringify(nodes)},
        data: { name: name },
        datatype: "json",
        asnyc: false,
        success: function (data) {
            if (data == true) {
                var treeObj = $.fn.zTree.getZTreeObj("GroupName");
                if (existence == true) {
                    var Pnode = treeObj.getNodeByParam("id", 1);
                    var newNodes = { name: name, icon: "../../../scripts/js/plugins/zTree-v3/css/zTreeStyle/img/diy/zzman.png", pId: 1 };
                    newNodes = treeObj.addNodes(Pnode, newNodes, isSilent = false);
                    var children = getchildren();
                    var newNode = children;
                    newNode = treeObj.addNodes(newNodes[0], newNode);
                }
                readDevices();
                readDevicesGroup();
                ztreeload();
                ztreeGroupload();
                alert("操作成功!");
                $('#addDeviceGroupDialog').dialog('close');

            } else {
            }
        }
    });

}


function deDeviceGroup() {
    var treeObj = $.fn.zTree.getZTreeObj("GroupName");
    var nodes = treeObj.getSelectedNodes();
    if (nodes.length != 0) {
        var p = nodes[0].id.substring(0, 1)
        if (p == "P") {
            alert("设备分组无法移动");
            return;
        }
        deleteDeviceGroup(nodes[0]);
        treeObj.removeNode(nodes[0]);
    }
    else {
        alert("请选择要移动的节点")
        return;
    }
}

function deleteDeviceGroup(treeNode) {
    if (treeNode.isParent == true) {
        var ZId = ""
        var PId = treeNode.id;
        if (typeof PId == "string") {
            PId = PId.replace("P", "");
        }

        for (var i = 0; i < treeNode.children.length; i++) {
            if (ZId != "") {
                ZId += ",";
                if (typeof treeNode.children[i].id == "string") {
                    ZId += (treeNode.children[i].id).replace("Z", "");
                }
            }
            else {
                ZId = treeNode.children[i].id;
                if (typeof ZId == "string") {
                    ZId = ZId.replace("Z", "");
                }
            }
        }
    }
    else if (treeNode.isParent == false && treeNode.pId == 1) {
        var PId = treeNode.id;
        if (typeof PId == "string") {
            PId = PId.replace("P", "");
        }
        var ZId = "";
    }
    else {
        var PId = "";
        var ZId = treeNode.id;
        if (typeof ZId == "string") {
            ZId = ZId.replace("Z", "");
        }
    }
    var groupid = -1;
    $.ajax({
        url: "/InstantPatrol/DelectDevicegroup",
        type: "post",
        data: { PId: PId, ZId: ZId, groupid: groupid },
        datatype: "json",
        asnyc: false,
        success: function (data) {
            if (data == true) {
                readDevices();
                readDevicesGroup();
                ztreeload();
                ztreeGroupload();
                alert("操作成功!");


            } else {

                alert("操作失败!");
            }
        }
    });

}
//添加分组
function AddGroup() {
    nodes = [];
    //poPupBox();
    $("#addDeviceGroupDialog").dialog("open");
    //清空
    $('#txtGroupName').val("");
}

function AddSubmit() {
    var name = $("#txtGroupName").val();
    if (name == "")
    {
       alert("分组名称不能为空!");
    }
    //添加、判重
    adddDeviceGroup(name, !ISexistence(name));
}

2.InstantPatrolController.cs

        #endregion
        #region  获取设备分组
        public List<DeviceGroup> GetTreeClass()
        {
            List<Serv_Petrol_Device> dlist = new List<Serv_Petrol_Device>();
            List<Serv_Device_Group> glist = new List<Serv_Device_Group>();
            using (var db = new DBH262Entities())
            {
                dlist = db.Serv_Petrol_Device.ToList();
                glist = db.Serv_Device_Group.ToList();

            }
            List<DeviceGroup> dglist = new List<DeviceGroup>();
            foreach (Serv_Petrol_Device model in dlist)
            {
                DeviceGroup dg = new DeviceGroup();
                dg.group_id = -1;
                dg.Id = model.Id;
                dg.group_name = model.group_name;
                dg.login_num = model.login_num;
                dg.login_time = model.login_time;
                dg.device_color = model.device_color;
                dg.device_name = model.device_name;
                dg.device_num = model.device_num;
                dg.device_type = model.device_type;
                foreach (Serv_Device_Group gmodel in glist)
                {
                    if (model.Id == gmodel.device_id)
                    {
                        dg.group_id = gmodel.group_id;
                    }
                }
                dglist.Add(dg);
            }

            return dglist;
        }
        /// <summary>
        /// 获取树
        /// </summary>
        /// <returns></returns>
        public JsonResult GetzTree()
        {
            List<DeviceGroup> list = new List<DeviceGroup>();
            list = GetTreeClass();
            var p = "P";
            var z = "Z";
            List<FixeddeviceGroupModel> Classlist = new List<FixeddeviceGroupModel>();
            FixeddeviceGroupModel deviceInfoModel;
            for (int a = 0; a < list.Count; a++)
            {
                if (list[a].group_id != -1)
                {
                    deviceInfoModel = new FixeddeviceGroupModel();
                    deviceInfoModel = new FixeddeviceGroupModel();
                    deviceInfoModel.id = z + list[a].Id;
                    deviceInfoModel.pid = p + (list[a].group_id).ToString();
                    deviceInfoModel.name = list[a].device_name;
                    Classlist.Add(deviceInfoModel);
                }
            }
            List<Serv_Group_Device> Device_Grouplist = new List<Serv_Group_Device>();
            using (var db = new DBH262Entities())
            {
                Device_Grouplist = db.Serv_Group_Device.ToList();
            }
            for (int a = 0; a < Device_Grouplist.Count; a++)
            {
                deviceInfoModel = new FixeddeviceGroupModel();
                deviceInfoModel.id = p + Device_Grouplist[a].ID;
                deviceInfoModel.pid = "";
                deviceInfoModel.deviceid = Device_Grouplist[a].ID;
                deviceInfoModel.name = Device_Grouplist[a].group_name;
                Classlist.Add(deviceInfoModel);
            }
            return Json(Classlist);
        }

        /// <summary>
        /// 获取树结构的设备信息
        /// </summary>
        /// <returns>设备信息</returns>
        [HttpPost]
        public JsonResult GetDevicesInfoTree()
        {
            List<DeviceGroup> list = new List<DeviceGroup>();
            list = GetTreeClass();
            return Json(list);
        }

        /// <summary>
        /// 添加设备分组
        /// </summary>
        /// <returns></returns>
        public JsonResult AddGroupInfo(FormCollection form)
        {
            string groupName = form["name"];



            if (!string.IsNullOrEmpty(groupName))
            {
                try
                {
                    using (var db = new DBH262Entities())
                    {
                        int count = db.Serv_Group_Device.Where(p => p.group_name == groupName).Count();
                        if (count > 0)
                            return Json(false);
                        Serv_Group_Device sgd = new Serv_Group_Device();
                        sgd.group_num = System.Guid.NewGuid().ToString();
                        sgd.group_name = groupName.Trim();
                        sgd.login_num = "";//当前用户
                        sgd.login_time = DateTime.Now;
                        db.Serv_Group_Device.Add(sgd);
                        db.SaveChanges();
                        return Json(true);
                    }
                }
                catch (Exception)
                {
                    return Json(false);
                }
            }
            else
            {
                return Json(false);
            }
        }
        /// <summary>
        /// 编辑设备分组
        /// </summary>
        /// <returns></returns>
        public JsonResult EditDevicegroup(string PId, string uName)
        {
            if (!string.IsNullOrEmpty(PId))
            {
                using (var db = new DBH262Entities())
                {
                    var entity = db.Serv_District_Config.Where(p => p.ID.ToString() == PId).FirstOrDefault();
                    entity.disname = uName;
                    db.SaveChanges();
                    return Json(true);
                }
            }
            else
            {
                return Json(false);
            }
        }
        /// <summary>
        /// 删除设备分组
        /// </summary>
        /// <returns></returns>
        /// <summary>
        public JsonResult DelectDevicegroup(string PId, string ZId, int groupid)
        {
            bool result = false;
            try
            {
                using (var db = new DBH262Entities())
                {
                    if (!string.IsNullOrEmpty(PId))
                    {
                        #region 删除设备分组
                        //分组下存在节点
                        if (!string.IsNullOrEmpty(ZId))
                        {
                            var entitySdg = db.Serv_Device_Group.Where(s => s.group_id.ToString() == PId).ToList();
                            db.Serv_Device_Group.RemoveRange(entitySdg);
                            var entity = db.Serv_Group_Device.Where(p => p.ID.ToString() == PId).FirstOrDefault();
                            db.Serv_Group_Device.Remove(entity);
                        }
                        //分组下无节点
                        else
                        {
                            var entity = db.Serv_Group_Device.Where(p => p.ID.ToString() == PId).FirstOrDefault();
                            db.Serv_Group_Device.Remove(entity);

                        }
                        result = true;
                        #endregion
                    }
                    else
                    {
                        #region 取消设备绑定的分组
                        if (!string.IsNullOrEmpty(ZId))
                        {
                            string[] siArray = ZId.Split(',');
                            for (int a = 0; a < siArray.Length; a++)
                            {
                                var entity = db.Serv_Device_Group.Where(p => p.device_id.ToString() == ZId).FirstOrDefault();
                                db.Serv_Device_Group.Remove(entity);
                            }
                            result = true;
                        }
                        #endregion
                    }
                    db.SaveChanges();
                    return Json(result);
                }
            }
            catch (Exception)
            {

                return Json(result);
            }

        }
        /// <summary>
        /// 设备移动到设备分组
        /// </summary>
        /// <returns></returns>
        /// <summary>
        [HttpPost]
        public JsonResult deviceMoveGroup(string deviceid, string groupid)
        {
            using (var db = new DBH262Entities())
            {
                deviceid = deviceid.TrimEnd(',');
                List<string> list = deviceid.Split(',').ToList();
                list.ForEach(p =>
                {
                    Serv_Device_Group sdg = new Serv_Device_Group();
                    sdg.group_id = int.Parse(groupid);
                    sdg.device_id = int.Parse(p);
                    db.Serv_Device_Group.Add(sdg);
                });


                db.SaveChanges();
                return Json(true);
            }
        }


        #endregion

3.View - Group.cshx

@{
    ViewBag.Title = "设备分组";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@*<h2>DeviceGroup</h2>*@

@section HeadCSS{
    @*<link href="~/style/base/css/deviceInfo.css" rel="stylesheet" />*@
    <!--artDialog-->
    @*<link href="~/scripts/js/plugins/artDialog/css/ui-dialog.css" rel="stylesheet" type="text/css" />*@
    <link href="~/style/base/css/popup.css" rel="stylesheet" />
    <link href="~/style/base/css/frame.css" rel="stylesheet" type="text/css" />
    @*<%--zTree--%>*@
    <link href="~/scripts/js/plugins/zTree-v3/css/zTreeStyle/zTreeStyle.css" rel="stylesheet" type="text/css" />
    <link href="~/style/base/css/patrol.css" rel="stylesheet" />

}

@section HeadJS{
    @*<script src="~/style/base/js/src/jquery-1.12.3.min.js"></script>*@
    <script src="~/st yle/base/js/src/jquery-2.1.1.min.js"></script>
    <script src="~/style/base/js/src/jquery.easyui.min.js"></script>
    <script src="~/scripts/js/common/communal.js" type="text/javascript"></script>
    @*<%--zTree--%>
        <script src="../../Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>*@
    <script src="~/scripts/js/plugins/zTree-v3/js/jquery.ztree.all.min.js" type="text/javascript"></script>
    <!--artDialog-->
    @*<script src="~/scripts/js/plugins/artDialog/dist/dialog-plus.js" type="text/javascript"></script>*@
    <script src="~/scripts/js/deviceInfo/DeviceGrouping.js" type="text/javascript"></script>

}

<script>
    $(function () {
        $(".schedM-config").dialog("close");
    })
</script>
<div class="content">
    <div class="tab  right-tab">
        <ul class="tab-ul">
            <li>
                <a href="/InstantPatrol/Index">
                    <h4>巡更设备</h4>
                </a>
            </li>
            <li>
                <a href="/InstantPatrol/Group">
                    <h4 class="pdirSelected">巡更组别</h4>
                </a>
            </li>
            <li>
                <a href="/InstantPatrol/Data">
                    <h4>巡更数据</h4>
                </a>
            </li>
            <li>
                <a href="/InstantPatrol/Configuration">
                    <h4>巡更配置</h4>
                </a>
            </li>
            <li>
                <a href="/InstantPatrol/RealTimeInspection">
                    <h4>实时巡查</h4>
                </a>
            </li>
        </ul>
        <label id="lab_alarm"></label>
    </div>
    <div class="patrol-group" style="margin-left:0">
        <div class="patrolGroup-box">
            <div class="patrolGroup-search">
                <input type="text" class="search-v search-v6" placeholder="请输入设备名称" id="deviceName">
                <input type="button" name="name" οnclick="ztreeload()" id="searchBut" class="btn btn-primary searchText">
                <input type="button" name="name" id="clearText" class="btn btn-primary clearText">

            </div>
            <div class="patrolGroup-btn">
                <button type="button" class="btn btn-primary query" οnclick="AddGroup()" id="Button1">添加分组</button>
            </div>
            <div class="patrolGroup-list">
                @*<div class="devicegroup-div">
                        <span class="group-list">设备分组列表</span>
                        <div class="wd-devicegroup">
                            <hr class="wd-hr" />
                            <div class="wd-dg-box">
                                <button οnclick="AddGroup()" id="Button1" type="button" class="btn btn-info addgroup">添加分组</button>
                                <ul id="GroupName" class="ztree GroupName"></ul>
                            </div>
                        </div>
                    </div>*@
                <div class="patrolGroup-l-left">
                    <p>设备分组列表</p>
                    <div class="patrolGroup-l-list">
                        <ul id="GroupName" class="ztree patrolGroup-l-list"></ul>
                    </div>
                </div>
                @*<div class="wd-dg-box2">
                        <img id="addshoubaoright" src="../../Style/base/images/public/right.png" οnclick="deDeviceGroup()" />
                        <img id="addshoubaoleft" src="../../Style/base/images/public/left.png" οnclick="addDeviceGroup()" />
                    </div>*@
                <div class="patrolGroup-l-center">
                    <div class="patrolGroup-bindright" id="addshoubaoright" οnclick="deDeviceGroup()"></div>
                    <div class="patrolGroup-bindleft" id="addshoubaoleft" οnclick="addDeviceGroup()"></div>
                </div>
                @*<div class="wd-dg-box3">
                        <span class="infolist">设备信息列表</span>
                        <div class="wd-dg-info">
                            <hr class="wd-hr" />
                            <div class="wd-dg-input">
                                <input type="text" class="form-control " id="deviceName" placeholder="请输入设备名称" style="Float:left"/>
                                <button οnclick="ztreeload()" id="searchBut" type="button" class="btn btn-info addgroup">搜索</button>
                                <ul id="devicetree" class="ztree devicetree"></ul>
                            </div>
                        </div>
                    </div>*@
                <div class="patrolGroup-l-right">
                    <p>设备信息列表</p>
                    <div class="patrolGroup-l-list">
                        <ul id="devicetree" class="ztree patrolGroup-l-list"></ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

<!--添加设备分组弹窗-->
<div id="addDeviceGroupDialog" class="easyui-dialog schedM-config" title="添加设备分组" width="380" height="200" style="display:none;">
    <div class="about-close"></div>
    @*<form action="/InstantPatrol/AddGroupInfo" method="post">*@
    <table align="center" style="margin:0 auto">
        <tr>
            <td><span class="mandatory-star">*</span>分组名称:</td>
            <td><input type="text" class="form-control" name="txtGroupName" id="txtGroupName" /></td>
        </tr>
    </table>
    <div class="TabFootBody">
        <div class="tabFoot">
            <input type="button" οnclick="AddSubmit()" name="name" value="提交" class="btn btn-default query" />
            <input type="button" name="name" value="取消" class="btn btn-default queryD" οnclick="$('#addDeviceGroupDialog').dialog('close');" />
        </div>
    </div>
    @*</form>*@
</div>
<!--学习就是不断积累的过程-->
展开阅读全文

没有更多推荐了,返回首页