html CheckBox MultiSelection - 复杂的JS工作(具有3级权限).html

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html CheckBox MultiSelection - 复杂的JS工作(具有3级权限).html相关的知识,希望对你有一定的参考价值。

@* ============================== AvailablePermission.cshtml ============================== *@
@model List<UserPrivilegeViewModel>
<div class="clearfix"></div>
<div class="box">
    <div class="box-body">
        @if (Model.Count > 0)
        {
            using (Ajax.BeginForm("AddEditPrivilege", "UserPrivilege", new { area = "Admin" },
                new AjaxOptions
                {
                    HttpMethod = "POST",
                    OnSuccess = "handleOnSuccess",
                    OnBegin = "Spiner.show()",
                    OnComplete = "Spiner.hide()"
                }))
            {
                @Html.AntiForgeryToken()
                <div class="">
                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                    <div class="table-responsive">
                        <table id="dataTable" class="table table-bordered table-hover">
                            <thead>
                                <tr>
                                    <th>Menu</th>
                                    <th style="text-align: left;"><label class="control-label" style="cursor: pointer;"><input type="checkbox" id="chkFullPermissionAll" class="header"/>&nbsp;Full Permission</label></th>

                                    @*@if (Settings.RoleId != 10){*@
                                        <th style="text-align: left;"><label class="control-label" style="cursor: pointer;"><input type="checkbox" id="chkViewAll" class="header"/>&nbsp;View</label></th>
                                        <th style="text-align: left;"><label class="control-label" style="cursor: pointer;"><input type="checkbox" id="chkAddAll" class="header" />&nbsp;Add</label></th>
                                        <th style="text-align: left;"><label class="control-label" style="cursor: pointer;"><input type="checkbox" id="chkEditAll" class="header" />&nbsp;Edit</label></th>
                                        <th style="text-align: left;"><label class="control-label" style="cursor: pointer;"><input type="checkbox" id="chkDeleteAll" class="header" />&nbsp;Delete</label></th>
                                        <th style="text-align: left;"><label class="control-label" style="cursor: pointer;"><input type="checkbox" id="chkDetailsAll" class="header" />&nbsp;Details</label></th>
                                        <th style="text-align: left;"><label class="control-label" style="cursor: pointer;"><input type="checkbox" id="chkReportAll" class="header"/>&nbsp;Report</label></th>
                                        <th style="text-align: left;"><label class="control-label" style="cursor: pointer;"><input type="checkbox" id="chkActiveAll" class="header" />&nbsp;IsActive</label></th>
                                    @*}*@
                                </tr>
                            </thead>
                            <tbody>
                                @Html.EditorForModel()
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-1 pull-right">
                        <input type="submit" value="Update" class="btn btn-primary pull-right" />
                    </div>
                </div>
            }
        }
        else
        {
            <strong>No data found!</strong>
        }
        <div class="row">
            @*@Html.PagedListPager(Model, page => Url.Action("NewAlert", new { page }), PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new PagedListRenderOptions { Display = PagedListDisplayMode.IfNeeded }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "newAlert" }))*@
        </div>

    </div>
</div>


<script>
    $(document).ready(function () {


        //$("#chkFullPermissionAll").click(function () {
        //    $(".chkFullPermissionAll").prop('checked', $(this).prop('checked'));
        //});
        //$("#chkViewAll").click(function () {
        //    $(".chkViewAll").prop('checked', $(this).prop('checked'));
        //});
  

        //Check All Checkbox on that column which is selected
        $(".header").click(function (e) {
            var idAsClass = e.target.getAttribute("id");
            //*************** ------ NOTE: Always keep the class name same as ID in 'UserPrivilegeViewModel.cshtml', otherwise it wont work!!!! 
            //*************** ------ Here assumed that 'Class' and 'Id' both having the same name.
            $("." + idAsClass).prop('checked', $(this).prop('checked'));
        });


        // CHECK ALL Chckboxes when FullPermission on Header is checked
        $("#chkFullPermissionAll").click(function (e) {
            $.each($("#dataTable>tbody>tr>td").find('input[type="checkbox"]'), function (thisRowIndex, thisRowItem) {
                thisRowItem["checked"] = $(e.target).prop('checked');;
            });
        });

        


        $(".module").click(function (e) {
            var checkedStatus = $(e.target).prop('checked');
            var id = e.target.getAttribute("data-id");
            var dataType = e.target.getAttribute("data-type");
            var parentId = e.target.getAttribute("data-parent-id"); //parentId of Module is Always Zero


            // CHECK ALL Columns of this row if FullPermission Column of parent is checked
            if (dataType === 'Full') {
                $.each($("#dataTable>tbody>tr>td").find('input[type="checkbox"][data-id="' + id + '"]'), function (thisRowIndex, thisRowItem) {
                    thisRowItem["checked"] = checkedStatus;
                });
            }


            // CHECK ALL CHILDS WHEN SELECTING MODULE (PARENT)
            $.each($("#dataTable>tbody>tr>td").find('input[type="checkbox"][data-parent-id="' + id + '"][data-type="' + dataType + '"]'), function (index, item) {
                
                // CHECK ALL FullPermission column of child
                item['checked'] = checkedStatus;


                if (dataType === 'Full') {
                    var childId = item.getAttribute("data-id");
                    var childParent = item.getAttribute("data-parent-id");


                    // CHECK ALL Column of this ROW, if the FullPermission is Clicked!
                    $.each($("#dataTable>tbody>tr>td").find('input[type="checkbox"][data-id="' + id + '"]'),function(thisRowIndex, thisRowItem) {
                            // CHECKING Childs
                            thisRowItem['checked'] = $(item).prop('checked');

                            // CHECKING GrandChilds
                            $.each($("#dataTable>tbody>tr>td").find('input[type="checkbox"][data-parent-id="' + childId + '"]'),function(_Index, _RowItem) {
                                    _RowItem['checked'] = $(item).prop('checked');
                            });
                    });


                    // CHECK ALL Column AND ALL ROWS OF CHILDS IF FullPermission is Checked on Parent
                    item['checked'] = checkedStatus;
                    $.each($("#dataTable>tbody>tr>td").find('input[type="checkbox"][data-id="' + childId + '"]'),function(index, childItem) {
                            childItem['checked'] = $(item).prop('checked');
                        });
                }
                else {
                    // CHECK/UNCHECK GrandChilds When Selecting ParentModule (Column except FullPermission)
                    var childId = item.getAttribute("data-id");
                    $.each($("#dataTable>tbody>tr>td").find('input[type="checkbox"][data-type="' + dataType + '"][data-parent-id="' + childId + '"]'), function (thisRowIndex, thisRowItem) {
                        thisRowItem['checked'] = $(item).prop('checked');
                    });
                }
            });

           



            // UNCHECK FullPermission When any of the other (Without 'Active' column)  permission is Unchecked! 
            if (dataType != 'Full') {
                var checkCount = 0;
                $.each($("#dataTable>tbody>tr>td").find('input[type="checkbox"][data-id="' + id + '"][data-type!="Full"][data-type!="Active"]'), function (thisRowIndex, thisRowItem) {
                    if ($(thisRowItem).prop('checked')) checkCount++;
                });
                if (checkCount == 6) $('input[type="checkbox"][data-id="' + id + '"]')[0].checked = true;
                 else $('input[type="checkbox"][data-id="' + id + '"]')[0].checked = false;
            }


            // UNCHECK IsActive When all of the other permission is Unchekced! (do this auto checking/unchecking only based on other column selection, not this IsActive column)
            if (dataType != 'Active') {
                var noSelect = 0;
                $.each($("#dataTable>tbody>tr>td").find('input[type="checkbox"][data-type!="Active"][data-id="' + id + '"]'), function (thisRowIndex, thisRowItem) {
                    if ($(thisRowItem).prop('checked')) noSelect++;
                });
                if (noSelect === 0) $('input[type="checkbox"][data-type="Active"][data-id="' + id + '"]')[0].checked = false;
                //else $('input[type="checkbox"][data-type="Active"][data-id="' + id + '"]')[0].checked = true;
            }



            //=====(N E E D  to R E F A C T O R) ============
            // CHECK / UNCHECKING FullPermission Column of parent and childs and grandChilds based on full column selection of all other permissions except IsActive 
            if (dataType != 'Full' && dataType != 'Active') {
                $.each($("#dataTable>tbody").find('tr[data-tr-id="' + id + '"],tr[data-tr-parent-id="' + id + '"]'), function (_trIndex, _trItem) {
                    var tempDataIdFull;
                    var menuCounter = 0;
                    var menuId = 0;
                    $.each($(_trItem).find('[type="checkbox"][data-type!="Full"][data-type!="Active"]'), function (_menuIndex, _menuItem) {
                        menuId = _menuItem.getAttribute("data-id");
                        tempDataIdFull = _menuItem.attributes["data-id"].value;
                        if ($(_menuItem).prop('checked')) menuCounter++;
                    });
                    if (menuCounter === 6) $('input[type="checkbox"][data-type="Full"][data-id="' + tempDataIdFull + '"]')[0].checked = true;
                    else $('input[type="checkbox"][data-type="Full"][data-id="' + tempDataIdFull + '"]')[0].checked = false;


                    // Selecting/Unselecting Grandchilds 
                    if (getChildTabCount(menuId) > 0) {
                        var grandChildIdFull;
                        var tabCheckCount = 0;
                        var currentDataId = 0;
                        $.each($("#dataTable>tbody>tr>td").find('[type="checkbox"][data-type!="Full"][data-type!="Active"][data-parent-id="' + menuId + '"]'), function (_tabIndex, _tabItem) {
                            if (currentDataId == 0) currentDataId = _tabItem.getAttribute("data-id");
                            if (currentDataId != 0 && $(_tabItem).prop('checked')) tabCheckCount++;
                            grandChildIdFull = _tabItem.attributes["data-id"].value;

                            if (tabCheckCount == 6) {
                                $('input[type="checkbox"][data-type="Full"][data-id="' + grandChildIdFull + '"]')[0].checked = true;
                                tabCheckCount = 0; currentDataId = 0;
                            }
                            else $('input[type="checkbox"][data-type="Full"][data-id="' + grandChildIdFull + '"]')[0].checked = false;
                        });
                    }
                });
            }
        });



        $(".menu").click(function (e) {
            var checkedStatus = $(e.target).prop('checked');
            var id = e.target.getAttribute("data-id");
            var parentId = e.target.getAttribute("data-parent-id");
            var dataType = e.target.getAttribute("data-type");


            // CHECK ALL Grand CHILDS When Selecting Menu 
            $.each($("#dataTable>tbody>tr>td").find('input[type="checkbox"][data-parent-id="' + id + '"][data-type="' + dataType + '"]'), function (index, item) {

                // CHECK ALL FullPermission column of child
                item['checked'] = checkedStatus;


                if (dataType === 'Full') {
                    var childId = item.getAttribute("data-id");
                    var childParent = item.getAttribute("data-parent-id");


                    // CHECK ALL Column of this ROW, if the FullPermission is Clicked!
                    $.each($("#dataTable>tbody>tr>td").find('input[type="checkbox"][data-id="' + id + '"]'), function (thisRowIndex, thisRowItem) {
                        // CHECKING Childs
                        thisRowItem['checked'] = $(item).prop('checked');
                    });


                    // CHECK ALL Column AND ALL ROWS OF CHILDS IF FullPermission is Checked on Parent
                    item['checked'] = checkedStatus;
                    $.each($("#dataTable>tbody>tr>td").find('input[type="checkbox"][data-id="' + childId + '"]'), function (index, childItem) {
                        childItem['checked'] = $(item).prop('checked');
                    });
                }
            });


            // CHECK/UNCHECK Parent based on Zero/More child selection
            var count = 0;
            $.each($("#dataTable>tbody>tr>td").find('input[type="checkbox"][data-parent-id="' + parentId + '"][data-type="' + dataType + '"]'), function (index, item) {
                if (item.checked) count++;
            });
            $('input[type="checkbox"][data-id="' + parentId + '"][data-type="' + dataType + '"]')[0].checked = count > 0; 



            // CHECK All Column when FullPermission of child is selected
            if (dataType === 'Full') {
                $.each($("#dataTable>tbody>tr>td").find('input[type="checkbox"][data-id="' + id + '"]'), function (index, item) {
                    item["checked"] = checkedStatus;
                });
            }


            // UNCHECK FullPermission When any of the other (Without 'Active' column)  permission is Unchecked! 
            if (dataType != 'Full') {
                var checkCount = 0;
                $.each($("#dataTable>tbody>tr>td").find('input[type="checkbox"][data-id="' + id + '"][data-type!="Full"][data-type!="Active"]'), function (thisRowIndex, thisRowItem) {
                    if ($(thisRowItem).prop('checked')) checkCount++;
                });
                if (checkCount === 6) $('input[type="checkbox"][data-id="' + id + '"]')[0].checked = true;
                else $('input[type="checkbox"][data-id="' + id + '"]')[0].checked = false;
            }


            // UNCHECK IsActive When all of the other permission is Unchekced! (do this auto checking/unchecking only based on other column selection, not this IsActive column)
            if (dataType != 'Active') {
                var noSelect = 0;
                $.each($("#dataTable>tbody>tr>td").find('input[type="checkbox"][data-type!="Active"][data-id="' + id + '"]'), function (thisRowIndex, thisRowItem) {
                    if ($(thisRowItem).prop('checked')) noSelect++;
                });
                if (noSelect === 0) $('input[type="checkbox"][data-type="Active"][data-id="' + id + '"]')[0].checked = false;
                //else $('input[type="checkbox"][data-type="Active"][data-id="' + id + '"]')[0].checked = true;
            }

            // CHECK / UNCHECKING FullPermission Column of parent and childs and grandChilds based on full column selection of all other permissions except IsActive 
            if (dataType != 'Full' && dataType != 'Active') {
                $.each($("#dataTable>tbody").find('tr[data-tr-id="' + id + '"],tr[data-tr-parent-id="' + id + '"]'), function (_trIndex, _trItem) {
                    var tempDataIdFull;
                    var menuCounter = 0;
                    var menuId = 0;
                    $.each($(_trItem).find('[type="checkbox"][data-type!="Full"][data-type!="Active"]'), function (_menuIndex, _menuItem) {
                        menuId = _menuItem.getAttribute("data-id");
                        tempDataIdFull = _menuItem.attributes["data-id"].value;
                        if ($(_menuItem).prop('checked')) menuCounter++;
                    });
                    if (menuCounter === 6) $('input[type="checkbox"][data-type="Full"][data-id="' + tempDataIdFull + '"]')[0].checked = true;
                    else $('input[type="checkbox"][data-type="Full"][data-id="' + tempDataIdFull + '"]')[0].checked = false;
                });
            }

        });



        $(".tab").click(function (e) {
            var checkedStatus = $(e.target).prop('checked');
            var id = e.target.getAttribute("data-id");
            var parentId = e.target.getAttribute("data-parent-id");
            var dataType = e.target.getAttribute("data-type");


            // CHECK/UNCHECK Parent based on Zero/More child selection
            var count = 0;
            $.each($("#dataTable>tbody>tr>td").find('input[type="checkbox"][data-parent-id="' + parentId + '"][data-type="' + dataType + '"]'), function (index, item) {
                if (item.checked) count++;
            });
            $('input[type="checkbox"][data-id="' + parentId + '"][data-type="' + dataType + '"]')[0].checked = count > 0;



            // CHECK All Column when FullPermission of child is selected
            if (dataType === 'Full') {
                $.each($("#dataTable>tbody>tr>td").find('input[type="checkbox"][data-id="' + id + '"]'), function (index, item) {
                    item["checked"] = checkedStatus;
                });
            }


            // UNCHECK FullPermission When any of the other (Without 'Active' column)  permission is Unchecked! 
            if (dataType != 'Full') {
                var checkCount = 0;
                $.each($("#dataTable>tbody>tr>td").find('input[type="checkbox"][data-id="' + id + '"][data-type!="Full"][data-type!="Active"]'), function (thisRowIndex, thisRowItem) {
                    if ($(thisRowItem).prop('checked')) checkCount++;
                });
                if (checkCount === 6) $('input[type="checkbox"][data-id="' + id + '"]')[0].checked = true;
                else $('input[type="checkbox"][data-id="' + id + '"]')[0].checked = false;
            }


            // UNCHECK IsActive When all of the other permission is Unchekced! (do this auto checking/unchecking only based on other column selection, not this IsActive column)
            if (dataType != 'Active') {
                var noSelect = 0;
                $.each($("#dataTable>tbody>tr>td").find('input[type="checkbox"][data-type!="Active"][data-id="' + id + '"]'), function (thisRowIndex, thisRowItem) {
                    if ($(thisRowItem).prop('checked')) noSelect++;
                });
                if (noSelect === 0) $('input[type="checkbox"][data-type="Active"][data-id="' + id + '"]')[0].checked = false;
                //else $('input[type="checkbox"][data-type="Active"][data-id="' + id + '"]')[0].checked = true;
            }
        });



        function getChildTabCount(parentId) {
            var counter = 0;
            $('#dataTable>tbody>tr>td').find('.tab[data-parent-id="' + parentId + '"]').each(function (i, obj) {
                counter++;
            });
            return counter;
        }

    });
    $(function () {
        var commentList = [];
        $.ajax({
            type: 'GET',
            async: false,
            dataType: 'json',
            url: '@Url.Action("GetComments","Home",new {Area=""})',
            success: function (result) {
                commentList = result;
            }
        });
        $(".commentBox").autocomplete({
            source: commentList
        });

        $('#customerNo').val('');
        $('#customerType').val('@ViewBag.CusType');
    });
    $(function () {
        sortingTable("#dataTable", "#AlertId,#CustomerNo,#FullName,#CustomerType,#Country,#RiskLevel,#RiskScore");
    });
</script>







@* ============================== UserPrivilegeViewModel.cshtml ============================== *@
@using Microsoft.Ajax.Utilities
@using VelocityFinCrime.Entity
@model UserPrivilegeViewModel

<tr class="dataItem" data-tr-id="@Model.MenuId" data-tr-parent-id="@Model.ParentId">

    @Html.HiddenFor(model => model.Id)
    @Html.HiddenFor(item => item.UserId)

    <td>

        @if (Model.MenuType == MenuType.Module)
        {
            <span class="glyphicon glyphicon-folder-open" aria-hidden="true">&nbsp;</span>
        }
        else if (Model.MenuType == MenuType.Menu)
        {
            <span style="padding-left: 30px;" class="glyphicon glyphicon-link" aria-hidden="true">&nbsp;</span>
        }
        else if (Model.MenuType == MenuType.Tab)
        {
            <span style="padding-left: 65px;" class="glyphicon glyphicon-tag" aria-hidden="true">&nbsp;</span>
        }
        @Html.DisplayFor(item => item.MenuName)
        @Html.HiddenFor(item => item.MenuId)

    </td>

    <td>
       @Html.CheckBoxFor(item => item.FullPermission, htmlAttributes: new {@class = "chkFullPermissionAll "+ Model.MenuType.ToString().ToLower() , @data_id = Model.MenuId, @data_parent_id = Model.ParentId, @data_type = "Full" })

        @*@if (@Settings.RoleId != 10){*@
    <td>
        @Html.CheckBoxFor(item => item.ViewPermission, htmlAttributes: new { @class = "chkViewAll " + Model.MenuType.ToString().ToLower(), @data_id = Model.MenuId, @data_parent_id = Model.ParentId, @data_type = "View" })
    </td>
    <td>
        @Html.CheckBoxFor(item => item.AddPermission, htmlAttributes: new { @class = "chkAddAll " + Model.MenuType.ToString().ToLower(), @data_id = Model.MenuId, @data_parent_id = Model.ParentId, @data_type = "Add" })
    </td>
    <td>
        @Html.CheckBoxFor(item => item.EditPermission, htmlAttributes: new { @class = "chkEditAll " + Model.MenuType.ToString().ToLower(), @data_id = Model.MenuId, @data_parent_id = Model.ParentId, @data_type = "Edit" })
    </td>
    <td>
        @Html.CheckBoxFor(item => item.DeletePermission, htmlAttributes: new { @class = "chkDeleteAll " + Model.MenuType.ToString().ToLower(), @data_id = Model.MenuId, @data_parent_id = Model.ParentId, @data_type = "Delete" })
    </td>
    <td>
        @Html.CheckBoxFor(item => item.DetailViewPermission, htmlAttributes: new { @class = "chkDetailsAll " + Model.MenuType.ToString().ToLower(), @data_id = Model.MenuId, @data_parent_id = Model.ParentId, @data_type = "Details" })
    </td>
    <td>
        @Html.CheckBoxFor(item => item.ReportViewPermission, htmlAttributes: new {@class = "chkReportAll " + Model.MenuType.ToString().ToLower(), @data_id = Model.MenuId, @data_parent_id = Model.ParentId, @data_type = "Report" })
    </td>
    <td>
        @Html.CheckBoxFor(item => item.IsActive, htmlAttributes: new { @class = "chkActiveAll " + Model.MenuType.ToString().ToLower(), @data_id = Model.MenuId, @data_parent_id = Model.ParentId, @data_type = "Active" })
    </td>
    @*}*@
</tr>






@* ============================== UserPrivilegeController.cs ============================== *@
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using VelocityFinCrime.Entity.Common.BusinessEntity;
using VelocityFinCrime.Entity.Common.GeneralEntity;
using VelocityFinCrime.Manager.Interface;
using VelocityFinCrime.Web.Security;

namespace VelocityFinCrime.Web.Areas.Admin.Controllers
{
    public class UserPrivilegeController : Controller
    {
        private readonly IUserManager _userManager;
        private readonly IBranchManager _branchManager;
        private readonly IUserPrivilegeManager _userPrivilegeManager;

        public UserPrivilegeController(IUserManager userManager
                                       , IBranchManager branchManager
                                       , IUserPrivilegeManager userPrivilegeManager
                                       )
        {
            _userManager = userManager;
            _branchManager = branchManager;
            _userPrivilegeManager = userPrivilegeManager;
        }
        [UserAuthorize]
        public ActionResult Index()
        {
            var x = _branchManager.GetAll();
            ViewData["lstBranch"] = _branchManager.GetAll();

            var list = new List<User>();
            IEnumerable<BranchUserViewModel> lstUser = _userManager.GetUserWithRoleByBranch(0).ToList();
            {
                var users = lstUser.ToList();
                foreach (var usr in users)
                {
                    list.Add(new User
                    {
                        Id = usr.UserId,
                        FullName = usr.UserName
                    });
                }
            }
            ViewData["lstUser"] = list;

            var model = new User();
            return PartialView(model);
        }
        [HttpGet]
        [UserAuthorize]
        public ActionResult AvailablePermission(User model)
        {
            var lstUserPrivilege = new List<UserPrivilegeViewModel>();
            List<UserPrivilegeViewModel> finalList = new List<UserPrivilegeViewModel>();
            if (model.Id != 0)
            {
                lstUserPrivilege = _userPrivilegeManager.GetByUserId(model.Id).OrderBy(x => x.ParentId).ToList();

                var hierarchy = _userPrivilegeManager.GetHierarchy(lstUserPrivilege);
                foreach (var item in hierarchy)
                {
                    if (item.Children.Count != 0)
                    {
                        finalList.Add(item);
                        foreach (var subItem in item.Children)
                        {
                            finalList.Add(subItem);
                            foreach (var thirdLevelItem in subItem.Children)
                            {
                                finalList.Add(thirdLevelItem);
                            }
                        }
                    }
                    else
                    {
                        finalList.Add(item);
                    }
                }
            }
            return PartialView(finalList);
        }
        [HttpGet]
        [UserAuthorize]
        public JsonResult GetUserByBranch(int? branchId)
        {
            int branch = branchId ?? 0;
            var list = new List<User>();

            IEnumerable<BranchUserViewModel> lstUser = _userManager.GetUserWithRoleByBranch(branch).ToList();
            {
                var users = lstUser.ToList();
                foreach (var usr in users)
                {
                    list.Add(new User
                    {
                        Id = usr.UserId,
                        FullName = usr.UserName
                    });
                }
            }


            return Json(new SelectList(list, "Id", "FullName"), JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        [UserAuthorize]
        public ActionResult AddEditPrivilege(List<UserPrivilegeViewModel> model)
        {
            foreach (var up in model)
            {
                if (up.Id == 0)
                {
                    _userPrivilegeManager.Create(up);
                }
                else
                {
                    _userPrivilegeManager.Update(up);
                }
            }

            return
                   Json(
                    new
                    {
                        redirectTo = Url.Action("Index", "UserPrivilege", new { Area = "Admin" }),
                        message = "Record updated Successfully !!!",
                        position = "mainContainer"
                    });
        }
    }
}




@* ============================== UserPrivilegeViewModel.cs ============================== *@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using VelocityFinCrime.Entity.Common.GeneralEntity;

namespace VelocityFinCrime.Entity.Common.BusinessEntity
{
    public class UserPrivilegeViewModel
    {
        public int Id { get; set; }
        public int UserId { get; set; }
        [Display(Name = "User Name")]
        public string UserName { get; set; }
        public virtual User User { get; set; }
        public int MenuId { get; set; }
        [Display(Name = "Menu Name")]
        public string MenuName { get; set; }

        public MenuType MenuType { get; set; }

        public int ParentId { get; set; }
        public virtual MenuConfig MenuConfig { get; set; }
        public bool IsActive { get; set; }
        public bool FullPermission { get; set; }
        public bool AddPermission { get; set; }
        public bool ViewPermission { get; set; }
        public bool EditPermission { get; set; }
        public bool DeletePermission { get; set; }
        public bool DetailViewPermission { get; set; }
        public bool ReportViewPermission { get; set; }

        public List<UserPrivilegeViewModel> Children { get; set; }
    }
}



@* ============================== UserPrivilege.cs ============================== *@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace VelocityFinCrime.Entity.Common.GeneralEntity
{
    [Table("UserPrivileges")]
   public class UserPrivilege
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        public int UserId { get; set; }
        [ForeignKey("UserId")]
        public virtual  User User { get; set; }
        public int MenuId { get; set; }
        [ForeignKey("MenuId")]
        public virtual MenuConfig  MenuConfig{ get; set; }
        public bool IsActive { get; set; }
        public bool FullPermission { get; set; }
        public bool AddPermission { get; set; }
        public bool ViewPermission { get; set; }
        public bool EditPermission { get; set; }
        public bool DeletePermission { get; set; }
        public bool DetailViewPermission { get; set; }
        public bool ReportViewPermission { get; set; }
    }
}




@* ============================== MenuType (enum) ============================== *@
  public enum MenuType
  {
      Module = 1,
      Menu = 2,
      Tab = 3
  }
    
    
    

@* ============================== UserPrivilegeManager.cs  ============================== *@

using PagedList;
using System;
using System.Collections.Generic;
using System.Linq;
using VelocityFinCrime.Entity.Common.BusinessEntity;
using VelocityFinCrime.Entity.Common.GeneralEntity;
using VelocityFinCrime.Manager.Interface;
using VelocityFinCrime.Repository.Common.Interface;

namespace VelocityFinCrime.Manager.Implementation
{
    public class UserPrivilegeManager : IUserPrivilegeManager
    {
        private IUserPrivilegeRepository _userPrivilegeRepository;
        private IUserRepository _userRepository;
        private IMenuConfigRepositoty _menuConfigRepositoty;
        public UserPrivilegeManager(IUserPrivilegeRepository userPrivilegeRepository
                                    , IUserRepository userRepository
                                    , IMenuConfigRepositoty menuConfigRepositoty
                                   )
        {
            _userPrivilegeRepository = userPrivilegeRepository;
            _userRepository = userRepository;
            _menuConfigRepositoty = menuConfigRepositoty;
        }

        public IEnumerable<UserPrivilegeViewModel> GetAll()
        {

            throw new NotImplementedException();

        }

        public IEnumerable<UserPrivilegeViewModel> GetByUserId(int id)
        {
            try
            {
                var usrInfo = from u in _userRepository.All()
                              join m in _menuConfigRepositoty.All() on u.RoleId equals m.RoleId
                              where u.Id == id
                              select new BranchUserViewModel
                              {
                                  UserId = u.Id,
                                  UserName = u.FullName,
                                  MenuId = m.Id,
                                  MenuName = m.MenuText
                              };

                var model = (from u in usrInfo
                             join mc in _menuConfigRepositoty.All() on u.MenuId equals mc.Id
                             join pp in _userPrivilegeRepository.All() on new { u.UserId, u.MenuId } equals new { pp.UserId, pp.MenuId } into lgj
                             from p in lgj.DefaultIfEmpty()
                             select new UserPrivilegeViewModel
                             {
                                 Id = p == null ? 0 : p.Id,
                                 MenuId = u.MenuId,
                                 MenuType = mc.MenuType,
                                 MenuName = u.MenuName,
                                 ParentId = mc.ParentId  ?? 0,
                                 UserId = u.UserId,
                                 UserName = u.UserName,
                                 IsActive = p != null && p.IsActive,
                                 FullPermission = p != null && p.FullPermission,
                                 AddPermission = p != null && p.AddPermission,
                                 EditPermission = p != null && p.EditPermission,
                                 ViewPermission = p != null && p.ViewPermission,
                                 DeletePermission = p != null && p.DeletePermission,
                                 DetailViewPermission = p != null && p.DetailViewPermission,
                                 ReportViewPermission = p != null && p.ReportViewPermission
                             }).Where(w => w.UserId == id).AsEnumerable();
                return model;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public UserPrivilege Get(int id)
        {
            throw new NotImplementedException();
        }

        public IEnumerable<UserPrivilege> GetAllActiveUser(bool activeStatus = true)
        {
            throw new NotImplementedException();
        }

        public IPagedList<UserPrivilege> GetAll(int page, int pageSize)
        {
            throw new NotImplementedException();
        }

        public UserPrivilege Create(UserPrivilegeViewModel model)
        {
            var itm = new UserPrivilege()
            {
                UserId = model.UserId,
                MenuId = model.MenuId,
                IsActive = model.IsActive,
                FullPermission = model.FullPermission,
                ViewPermission = model.ViewPermission,
                AddPermission = model.AddPermission,
                EditPermission = model.EditPermission,
                DeletePermission = model.DeletePermission,
                DetailViewPermission = model.DetailViewPermission,
                ReportViewPermission = model.ReportViewPermission
            };

            return _userPrivilegeRepository.Create(itm);
        }

        public int Update(UserPrivilegeViewModel model)
        {
            var itm = new UserPrivilege()
            {
                Id = model.Id,
                UserId = model.UserId,
                MenuId = model.MenuId,
                IsActive = model.IsActive,
                FullPermission = model.FullPermission,
                ViewPermission = model.ViewPermission,
                AddPermission = model.AddPermission,
                EditPermission = model.EditPermission,
                DeletePermission = model.DeletePermission,
                DetailViewPermission = model.DetailViewPermission,
                ReportViewPermission = model.ReportViewPermission
            };

            return _userPrivilegeRepository.Update(itm);
        }

        public List<UserPrivilegeViewModel> GetHierarchy(List<UserPrivilegeViewModel> listPrivileges)
        {
            var hierarchy = listPrivileges.Where(module => module.ParentId == 0).Select(module => new UserPrivilegeViewModel
            {
                Id = module.Id,
                MenuName = module.MenuName,
                ParentId = module.ParentId,
                UserId = module.UserId,
                UserName = module.UserName,
                MenuId = module.MenuId,
                MenuType = module.MenuType,
                IsActive = module.IsActive,
                FullPermission = module.FullPermission,
                AddPermission = module.AddPermission,
                ViewPermission = module.ViewPermission,
                EditPermission = module.EditPermission,
                DeletePermission = module.DeletePermission,
                DetailViewPermission = module.DetailViewPermission,
                ReportViewPermission = module.ReportViewPermission,
                Children = listPrivileges.Where(menu => menu.ParentId == module.MenuId).Select(menu => new UserPrivilegeViewModel
                {
                    Id = menu.Id,
                    MenuName = menu.MenuName,
                    ParentId = menu.ParentId,
                    UserId = menu.UserId,
                    UserName = menu.UserName,
                    MenuId = menu.MenuId,
                    MenuType = menu.MenuType,
                    IsActive = menu.IsActive,
                    FullPermission = menu.FullPermission,
                    AddPermission = menu.AddPermission,
                    ViewPermission = menu.ViewPermission,
                    EditPermission = menu.EditPermission,
                    DeletePermission = menu.DeletePermission,
                    DetailViewPermission = menu.DetailViewPermission,
                    ReportViewPermission = menu.ReportViewPermission,
                    Children = listPrivileges.Where(tab => tab.ParentId == menu.MenuId).Select(tab => new UserPrivilegeViewModel
                    {
                        Id = tab.Id,
                        MenuName = tab.MenuName,
                        ParentId = tab.ParentId,
                        UserId = tab.UserId,
                        UserName = tab.UserName,
                        MenuId = tab.MenuId,
                        MenuType = tab.MenuType,
                        IsActive = tab.IsActive,
                        FullPermission = tab.FullPermission,
                        AddPermission = tab.AddPermission,
                        ViewPermission = tab.ViewPermission,
                        EditPermission = tab.EditPermission,
                        DeletePermission = tab.DeletePermission,
                        DetailViewPermission = tab.DetailViewPermission,
                        ReportViewPermission = tab.ReportViewPermission,
                        Children = null
                    }).ToList()
                }).ToList()
            }).ToList();

            return hierarchy;
        }
    }
}







@* ==============================  ============================== *@

以上是关于html CheckBox MultiSelection - 复杂的JS工作(具有3级权限).html的主要内容,如果未能解决你的问题,请参考以下文章

[DevExpress] GridControl自定义复选框(checkbox),无须绑定数据源字段。

DevExpress GridControl自定义复选框(checkbox),无须绑定数据源字段。

html 破碎multiselect.html

JS组件系列——两种bootstrap multiselect组件大比拼

在数据文件属性中显示复选框值

如何在 MVC 中实现 MultiSelect 下拉列表