Asp.Net MVC+BootStrap+EF6.0實現簡單的用戶角色權限管理7


做完角色之后接下來做先做頁面按鈕的增加、刪除、修改。這里用到的功能和角色那邊是一樣的。就不多說了。直接上代碼。

后台控制器代碼

using AuthorDesign.Web.App_Start.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AuthorDesign.Web.Areas.Admin.Controllers {
    public class PageActionController : Controller {
        //
        // GET: /Admin/PageAction/

        public ActionResult PageActionList() {
            ViewBag.Title = "頁面按鈕列表";
            return View();
        }
        /// <summary>
        /// 獲取列表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult PageActionList(Models.ButtonParamModel model) {
            int rowCount = 0;
            var result = EnterRepository.GetRepositoryEnter().GetPageActionRepository.LoadPageList(model.iDisplayStart, model.iDisplayLength, model.IsDesc, out rowCount);
            return Json(new {
                sEcho = model.sEcho,
                iTotalRecords = rowCount,
                iTotalDisplayRecords = rowCount,
                aaData = result
            }, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 獲取按鈕信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetPageActionInfo(int id = 0) {
            var result = EnterRepository.GetRepositoryEnter().GetPageActionRepository.LoadEntities(m => m.Id == id).FirstOrDefault();
            if (result == null) {
                return Json(new { state = "error", message = "按鈕不存在" });
            }
            else {
                return Json(new { state = "success", result });
            }
        }
        /// <summary>
        /// 添加頁面按鈕
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult AddPageAction(Models.PageActionModel model) {
            if (ModelState.IsValid) {
                IDAL.IPageActionRepository pageActionRepository = EnterRepository.GetRepositoryEnter().GetPageActionRepository;
                //判斷頁面按鈕代碼是否已存在
                var result = pageActionRepository.LoadEntities(m => m.ActionCode == model.ActionCode.Trim()).FirstOrDefault();
                if (result == null) {
                    pageActionRepository.AddEntity(new Model.PageAction() {
                        ActionCode = model.ActionCode,
                        ActionLevel = model.ActionLevel,
                        IsShow = model.IsShow,
                        Name = model.Name
                    });
                    //添加下操作記錄
                    PublicFunction.AddOperation(1, string.Format("添加頁面按鈕"), string.Format("添加角色=={0}==頁面按鈕成功", model.Name));
                    if (EnterRepository.GetRepositoryEnter().SaveChange() > 0) {
                        return Json(new {
                            state = "success",
                            message = "添加頁面按鈕成功"
                        });
                    }
                    else {
                        PublicFunction.AddOperation(1, string.Format("添加頁面按鈕"), string.Format("添加頁面按鈕=={0}==失敗", model.Name));
                        EnterRepository.GetRepositoryEnter().SaveChange();
                        return Json(new {
                            state = "error",
                            message = "添加頁面按鈕失敗"
                        });
                    }
                }
                else {
                    return Json(new {
                        state = "error",
                        message = "頁面按鈕代碼已經存在了"
                    });
                }
            }
            else {
                return Json(new {
                    state = "error",
                    message = "信息不完整"
                });
            }
        }
        /// <summary>
        /// 修改頁面按鈕
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdatePageAction(Models.PageActionModel model) {
            if (ModelState.IsValid && model.Id > 0) {
                IDAL.IPageActionRepository pageActionRepository = EnterRepository.GetRepositoryEnter().GetPageActionRepository;
                //判斷權限名稱是否已存在
                var result = pageActionRepository.LoadEntities(m => m.ActionCode == model.ActionCode.Trim()).FirstOrDefault();
                if (result != null && result.Id != model.Id) {
                    return Json(new {
                        state = "error",
                        message = "頁面按鈕代碼已經存在了"
                    });
                }
                else {
                    Model.PageAction pageAction = new Model.PageAction() {
                        ActionCode = model.ActionCode,
                        ActionLevel = model.ActionLevel,
                        IsShow = model.IsShow,
                        Name = model.Name,
                        Id = model.Id
                    };
                    pageActionRepository.Get(m => m.Id == model.Id);
                    pageActionRepository.EditEntity(pageAction, new string[] { "ActionCode", "ActionLevel", "IsShow", "Name" });
                    PublicFunction.AddOperation(1, string.Format("修改頁面按鈕"), string.Format("修改頁面按鈕=={0}==成功", model.Name));
                    if (EnterRepository.GetRepositoryEnter().SaveChange() > 0) {
                        return Json(new {
                            state = "success",
                            message = "修改頁面按鈕成功"
                        });
                    }
                    else {
                        PublicFunction.AddOperation(1, string.Format("修改頁面按鈕"), string.Format("修改頁面按鈕=={0}==失敗", model.Name));
                        EnterRepository.GetRepositoryEnter().SaveChange();
                        return Json(new {
                            state = "error",
                            message = "修改頁面按鈕失敗"
                        });
                    }
                }
            }
            else {
                return Json(new {
                    state = "error",
                    message = "信息不完整"
                });
            }
        }

        /// <summary>
        /// 更改按鈕狀態
        /// </summary>
        /// <param name="id">按鈕Id</param>
        /// <param name="state">按鈕狀態</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdateState(int id = 0, int state = 0) {
            EnterRepository.GetRepositoryEnter().GetPageActionRepository.EditEntity(new Model.PageAction() { Id = id, IsShow = (byte)state }, new string[] { "IsShow" });
            PublicFunction.AddOperation(1, string.Format("修改按鈕狀態"), string.Format("修改按鈕狀態成功"));
            if (EnterRepository.GetRepositoryEnter().SaveChange() > 0) {
                return Json(new { state = "success", message = "修改按鈕狀態成功" });
            }
            else {
                PublicFunction.AddOperation(1, string.Format("修改按鈕狀態"), string.Format("修改按鈕狀態失敗"));
                EnterRepository.GetRepositoryEnter().SaveChange();
                return Json(new { state = "error", message = "服務器泡妞去了" });
            }
        }
    }
}
View Code

頁面代碼

@section Header{
    <style type="text/css">
        /*加載動態圖片*/
        .dataTables_processing {
            position: absolute;
            top: 50%;
            left: 50%;
            width: 100%;
            height: 40px;
            margin-left: -50%;
            margin-top: -25px;
            padding-top: 20px;
            text-align: center;
            font-size: 1.2em;
            /*background-color: white;*/
        }
    </style>
}

<div class="main-content">
    <div class="breadcrumbs" id="breadcrumbs">
        <script type="text/javascript">
            try { ace.settings.check('breadcrumbs', 'fixed') } catch (e) { }
        </script>

        <ul class="breadcrumb">
            <li>
                <i class="icon-home home-icon"></i>
                <a href="/Admin/Home">首頁</a>
            </li>
            <li>
                <a href="/Admin/PageAction/PageActionList">頁面按鈕列表</a>
            </li>
            <li class="active">頁面按鈕列表</li>
        </ul><!-- .breadcrumb -->
        <!-- #nav-search -->
    </div>
    <div class="page-content">
        <div class="row">
            <div class="col-xs-12">
                <!-- PAGE CONTENT BEGINS -->

                <div class="row">
                    <div class="col-xs-12">
                        <div class="table-header">
                            頁面按鈕列表查看
                        </div>
                        <div class="hidden" id="hidden_filter">
                            @* 把需要搜索的條件放到hidden里面,在table格式化完成的時候直接調用$.html()賦值,免去了在js拼接標簽的麻煩 *@
                            <div style="float:left;">
                                <label class="AddRole">
                                    <a id="AddNewButton" class="btn btn-xs btn-primary" data-toggle="modal" href="" onclick="showAddNewAdmin()" title="添加新按鈕">
                                        <i class="icon-plus-sign bigger-130"></i>
                                        添加新按鈕
                                    </a>
                                </label>
                            </div>
                        </div>
                        <div class="table-responsive dataTables_wrapper">
                            <table id="sample-table-2" class="table table-striped table-bordered table-hover">
                                <thead>
                                    <tr>
                                        <th class="center sorting_disabled" role="columnheader" rowspan="1" colspan="1" aria-label="" style="width: 58px;">
                                            <label>
                                                <input type="checkbox" class="ace">
                                                <span class="lbl"></span>
                                            </label>
                                        </th>
                                        <th>動作名稱</th>
                                        <th>動作代碼</th>
                                        <th>是否顯示</th>
                                        <th>動作等級</th>
                                        <th style="width: 120px;">
                                            操作
                                        </th>
                                    </tr>
                                </thead>
                            </table>
                        </div>
                    </div>
                </div>
                <!-- PAGE CONTENT ENDS -->
            </div><!-- /.col -->
        </div><!-- /.row -->
    </div><!-- /.page-content -->
</div>
<div class="modal fade" id="ShowAdd" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    @RenderPage("/Areas/Admin/Views/PageAction/DisplayTemplates/PageAction.cshtml")
</div>
@section script{
    <script src="/Content/assets/js/jquery.dataTables.min.js"></script>
    <script src="/Content/assets/js/jquery.dataTables.bootstrap.js"></script>
    <script src="/Content/assets/js/bootbox.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

    <script type="text/javascript">
        var isSearch = false;
        $(function () {
            var objTable = $("#sample-table-2").dataTable({
                aoColumns: [
                    { "sClass": "center", "mDataProp": "Id", "bSortable": false },
                    { "sClass": "center", "mDataProp": "Name", "bSortable": false },
                    { "sClass": "center", "mDataProp": "ActionCode", "bSortable": false },
                    { "sClass": "center", "mDataProp": "IsShow", "bSortable": false },
                    { "mDataProp": "ActionLevel", "sClass": "center", "bSortable": true, "asSorting": ["asc", "desc"] },
                    {
                        "sClass": "center",
                        "mDataProp": "Id",
                        "bSortable": false
                    }
                ],
                "bServerSide": true,//分頁,取數據等等的都放到服務端去
                "bProcessing": true,//載入數據的時候是否顯示“載入中”
                "aLengthMenu": [30, 50, 100],
                "bLengthChange": true, //改變每頁顯示數據數量
                //"bFilter": false, //過濾功能
                "iDisplayStart": 0,
                "iDisplayLength": 30,//首次加載的數據條數
                "bStorable": true,//排序操作在服務端進行,所以可以關了。
                "sAjaxSource": "/Admin/PageAction/PageActionList",
                "fnServerParams": function (aoData, bStorable) {
                },
                /*如果加上下面這段內容,則使用post方式傳遞數據*/
                "fnServerData": function (sSource, aoData, fnCallback, bStorable) {
                    var paramList = {
                        "sEcho": 0,
                        "iDisplayLength": 0,
                        "iDisplayStart": 0,
                        "isDesc": bStorable.aaSorting[0][1] == "desc" ? true : false
                    };
                    if (bStorable.aaSorting[0][0] == 0) {
                        paramList.isDesc = true;
                    }
                    for (var i = 0; i < aoData.length; i++) {
                        if (aoData[i].name == "iDisplayStart") {
                            paramList.iDisplayStart = aoData[i].value;
                        } else if (aoData[i].name == "iDisplayLength") {
                            paramList.iDisplayLength = aoData[i].value;
                        } else if (aoData[i].name == "sEcho") {
                            paramList.sEcho = aoData[i].value;
                        }
                    }
                    $.ajax({
                        "dataType": 'json',
                        "type": "POST",
                        "url": sSource,
                        "data": paramList,
                        "success": function (resp) {
                            fnCallback(resp); //服務器端返回的對象的returnObject部分是要求的格式
                        }
                    });
                },
                "oLanguage": {
                    "sSearch": "搜索",
                    "sLengthMenu": "每頁顯示 _MENU_ 條記錄",
                    "sZeroRecords": "抱歉, 沒有找到",
                    "sInfo": "從 _START_ 到 _END_ 共 _TOTAL_ 條數據",
                    "sInfoEmpty": "沒有數據",
                    "sInfoFiltered": "(從 _MAX_ 條數據中檢索)",
                    "oPaginate": {
                        "sFirst": "首頁",
                        "sPrevious": "前一頁",
                        "sNext": "后一頁",
                        "sLast": "尾頁"
                    },
                    "sZeroRecords": "沒有檢索到數據",
                    "sProcessing": "<img src='/Content/assets/images/loading.gif' />"
                },
                "fnRowCallback": function (nRow, aData, iDisplayIndex) {  /* 用來改寫指定行的樣式 */
                    $('td:eq(0)', nRow).html("<label><input type=\"checkbox\" class=\"ace\" value=\"" + aData.Id + "\"><span class=\"lbl\"></span></label>");
                    
                    var html = "<div class=\"visible-md visible-lg hidden-sm hidden-xs action-buttons\">";
                    html += "<a class=\"green LookRole\" href=\"javascript:UpdateObj('" + aData.Id + "')\" title=\"編輯\"><i class=\"icon-pencil bigger-130\"></i></a>";//編輯
                    if (aData.IsShow == 0) {
                        html += "<a class=\"green UpdateRole\" href=\"javascript:CanShow('" + aData.Id + "',1)\" title=\"設置顯示\"><i class=\"icon-ok bigger-130\"></i></a>";
                        $('td:eq(3)', nRow).html("<i class=\"icon-remove red bigger-120\"></i>");
                    }
                    else {
                        html += "<a class=\"red UpdateRole\" href=\"javascript:CanShow('" + aData.Id + "',0)\" title=\"設置不顯示\"><i class=\"icon-remove bigger-130\"></i></a>";//刪除
                        $('td:eq(3)', nRow).html("<i class=\"icon-ok green bigger-120\"></i>");
                    }
                    html += "</div>";
                    $('td:eq(5)', nRow).html(html);
                    return nRow;
                }
            });
            //下面的代碼主要是將下拉框的位置已到右邊去
            $("#sample-table-2_length").parents().first().removeClass("col-sm-6").addClass("col-sm-3");
            $("#sample-table-2_length").parents().first().css("float", "right");
            $("#sample-table-2_filter").parents().first().removeClass("col-sm-6").addClass("col-sm-8");
            $("#sample-table-2_filter").parents().first().css("float", "left");
            $("#sample-table-2_length").css("float", "right");
            $("#sample-table-2_filter").html($("#hidden_filter").html());
            $("#hidden_filter").remove();
        })

        function showAddNewAdmin() {
            $("#Id").val(0);
            $('#ShowAdd').modal();
        }
        function UpdateObj(id) {
            $.ajax({
                type: "post",
                data: { id: id },
                url: "/Admin/PageAction/GetPageActionInfo",
                success: function (result) {
                    if (result.state == "success") {
                        $("#Id").val(id);
                        $("#Name").val(result.result.Name);
                        $("#ActionCode").val(result.result.ActionCode);
                        $("#ActionLevel").val(result.result.ActionLevel);
                        if (result.result.IsShow == 0) {
                            $("input[name='IsShow']").eq(0).removeAttr("checked");
                            $("input[name='IsShow']").eq(1).attr("checked", "checked");
                        }
                        else {
                            $("input[name='IsShow']").eq(0).attr("checked", "checked");
                            $("input[name='IsShow']").eq(1).removeAttr("checked");
                        }
                        $('#ShowAdd').modal();
                    } else {
                        bootbox.alert({
                            buttons: {
                                ok: {
                                    label: '我知道了',
                                    className: 'btn btn-primary'
                                }
                            }, callback: function () {
                            },
                            message: result.message
                        });
                    }
                }
            })
        }
        $("#AddRoleForm").submit(function () {
            if ($("#AddRoleForm").valid()) {
                var url = "/Admin/PageAction/AddPageAction";
                if ($("#Id").val() > 0) {
                    url = "/Admin/PageAction/UpdatePageAction";
                }
                $.ajax({
                    type: "post",
                    data: $("#AddRoleForm").serialize(),
                    url: url,
                    success: function (result) {
                        if (result.state == "success") {
                            $('#ShowAdd').modal('hide');//關閉模態框
                            document.getElementById("AddRoleForm").reset();//清空表單
                            bootbox.alert({
                                buttons: {
                                    ok: {
                                        label: '我知道了',
                                        className: 'btn btn-primary'
                                    }
                                }, callback: function () {
                                    $("#sample-table-2").dataTable().fnDraw();//點搜索重新繪制table。
                                },
                                message: result.message
                            });
                        } else {
                            bootbox.alert({
                                buttons: {
                                    ok: {
                                        label: '我知道了',
                                        className: 'btn btn-primary'
                                    }
                                }, callback: function () {
                                },
                                message: result.message
                            });
                        }
                    }
                })
                return false;
            }
            else {
                return false;
            }
        })

        function CanShow(id, state) {
            bootbox.confirm({
                buttons: {
                    confirm: {
                        label: '確定',
                        className: 'btn-primary'
                    },
                    cancel: {
                        label: '取消',
                        className: 'btn-default'
                    }
                },
                message: state == 0 ? "確定該按鈕不顯示嗎" : "確定該按鈕顯示嗎",
                callback: function (result) {
                    if (result) {
                        UpdateState(id, state)
                    }
                }
            });
        }
        function UpdateState(id, state) {
            $.ajax({
                type: "post",
                data: { id: id, state: state },
                url: "/Admin/PageAction/UpdateState",
                success: function (result) {
                    if (result.state == "success") {
                        bootbox.alert({
                            buttons: {
                                ok: {
                                    label: '我知道了',
                                    className: 'btn btn-primary'
                                }
                            }, callback: function () {
                                $("#sample-table-2").dataTable().fnDraw();//點搜索重新繪制table。
                            },
                            message: result.message
                        });
                    } else {
                        bootbox.alert({
                            buttons: {
                                ok: {
                                    label: '我知道了',
                                    className: 'btn btn-primary'
                                }
                            }, callback: function () {
                            },
                            message: result.message
                        });
                    }
                }
            })
        }
    </script>
}



@model AuthorDesign.Web.Areas.Admin.Models.PageActionModel

<div class="main-content col-xs-8" style="margin-top: 70px; margin-left: 15%;">
    <div class="page-content">
        <div class="row">
            <section>
                <div class="page-header">
                    <h1>
                        管理
                        <small>
                            <i class="icon-double-angle-right"></i>
                            <span id="ShowText">頁面按鈕編輯</span>
                        </small>
                    </h1>
                </div>
                <div class="col-lg-10 col-lg-offset-2">
                    <form id="AddRoleForm" class="form-horizontal">
                        <fieldset>
                            @Html.HiddenFor(m => m.Id)
                            <div class="form-group">
                                <label class="col-lg-3 control-label">按鈕名稱<span style="color:red;">*</span>:</label>
                                <div class="col-lg-7" style="float:left;">
                                    @Html.TextBoxFor(m => m.Name, new { @class = "col-sm-8" })
                                    @Html.ValidationMessageFor(m => m.Name)
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-3 control-label">按鈕代碼<span style="color:red;">*</span>:</label>
                                <div class="col-lg-7">
                                    @Html.TextBoxFor(m => m.ActionCode, new { @class = "col-sm-8" })
                                    @Html.ValidationMessageFor(m => m.ActionCode)
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-3 control-label">動作等級:</label>
                                <div class="col-lg-7">
                                    @Html.TextBoxFor(m => m.ActionLevel, new { @class = "col-sm-8" })
                                    @Html.ValidationMessageFor(m => m.ActionLevel)
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-3 control-label">是否顯示</label>
                                <div class="col-lg-7">
                                    <label>
                                        <input name="IsShow" type="radio" class="ace" value="1" checked="checked" />
                                        <span class="lbl">顯示</span>
                                    </label>
                                    <label>
                                        <input name="IsShow" type="radio" class="ace" value="0" />
                                        <span class="lbl">不顯示</span>
                                    </label>
                                </div>
                            </div>
                        </fieldset>
                        <div class="form-group">
                            <div class="col-lg-9 col-lg-offset-3">
                                <button class="btn btn-primary UpdateRole" type="submit">
                                    <i class="icon-ok bigger-110"></i>
                                    保存
                                </button>
                                <button class="btn" type="reset" data-dismiss="modal">
                                    <i class="icon-undo bigger-110"></i>
                                    取消
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </section>
            <!-- /.row -->
        </div>
    </div>
    <!-- /.page-content -->
</div>
View Code

頁面執行效果

做完頁面按鈕的時候本來想先去做頁面的增刪改查的,但是發現頁面的樣式有點難找,就先弄了管理員的增加修改刪除

首先也是控制器的代碼

using AuthorDesign.Common;
using AuthorDesign.Web.App_Start.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AuthorDesign.Web.Areas.Admin.Controllers
{
    public class AdminController : Controller
    {
        //
        // GET: /Admin/Admin/

        public ActionResult AdminList()
        {
            ViewBag.Title = "管理員列表";
            ViewBag.RoleSelectItem = SelectItemHelper.GetRoleItemList(0);
            return View();
        }
        [HttpPost]
        public JsonResult AdminList(Models.AdminParamModel model) {
            int rowCount = 0;
            var result = EnterRepository.GetRepositoryEnter().GetAdminRepository.LoadPageList(model.RoleId, model.Mobile, model.iDisplayStart, model.iDisplayLength, model.IsDesc, out rowCount);
            return Json(new {
                sEcho = model.sEcho,
                iTotalRecords = rowCount,
                iTotalDisplayRecords = rowCount,
                aaData = result
            }, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 獲取管理員信息
        /// </summary>
        /// <param name="id">管理員Id</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetAdminInfo(int id = 0) {
            var result = EnterRepository.GetRepositoryEnter().GetAdminRepository.LoadEntities(m => m.Id == id && m.IsSuperAdmin == 0).FirstOrDefault();
            if (result == null) {
                return Json(new { state = "error", message = "無法找到該管理員信息" });
            }
            else {
                return Json(new { state = "success", result });
            }
        }
        /// <summary>
        /// 添加管理員
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult AddAdmin(Models.AdminModel model) {
            if (ModelState.IsValid) {
                IDAL.IAdminRepository adminRepository = EnterRepository.GetRepositoryEnter().GetAdminRepository;
                //判斷權限名稱是否已存在
                var result = adminRepository.LoadEntities(m => m.Mobile == model.Mobile.Trim()).FirstOrDefault();
                if (result == null) {
                    Random rn = new Random();
                    string salt = rn.Next(10000, 99999).ToString() + rn.Next(10000, 99999).ToString();
                    adminRepository.AddEntity(new Model.Admin() {
                        AuthoryId = model.AuthoryId,
                        CreateTime = DateTime.Now,
                        IsLogin = model.IsLogin,
                        Mobile = model.Mobile,
                        IsSuperAdmin = 0,
                        LastLoginTime = DateTime.Now,
                        Salt = salt,
                        Password = MD5Helper.CreatePasswordMd5("ad" + model.Mobile.Substring(7, 4), salt)
                    });
                    //添加下操作記錄
                    PublicFunction.AddOperation(1, string.Format("添加管理員"), string.Format("添加管理員=={0}==成功", model.Mobile));
                    if (EnterRepository.GetRepositoryEnter().SaveChange() > 0) {
                        return Json(new {
                            state = "success",
                            message = "添加管理員成功"
                        });
                    }
                    else {
                        PublicFunction.AddOperation(1, string.Format("添加管理員"), string.Format("添加管理員=={0}==失敗", model.Mobile));
                        EnterRepository.GetRepositoryEnter().SaveChange();
                        return Json(new {
                            state = "error",
                            message = "添加管理員失敗"
                        });
                    }
                }
                else {
                    return Json(new {
                        state = "error",
                        message = "手機號碼已經存在了"
                    });
                }
            } else {
                return Json(new { state="error",message="信息不完整"});
            }
        }
        /// <summary>
        /// 修改管理員
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdateAdmin(Models.AdminModel model) {
            if (ModelState.IsValid) {
                IDAL.IAdminRepository adminRepository = EnterRepository.GetRepositoryEnter().GetAdminRepository;
                //判斷權限名稱是否已存在
                var result = adminRepository.LoadEntities(m => m.Mobile == model.Mobile.Trim()).FirstOrDefault();
                if (result != null && result.Id != model.Id) {
                    return Json(new {
                        state = "error",
                        message = "手機號碼已經存在了"
                    });
                }
                else {
                    Model.Admin admin = new Model.Admin() {
                        AuthoryId = model.AuthoryId,
                        IsLogin = model.IsLogin,
                        Mobile = model.Mobile,
                        Id = model.Id
                    };
                    //清楚context中result對象
                    adminRepository.Get(m => m.Id == model.Id);
                    adminRepository.EditEntity(admin, new string[] { "AuthoryId", "IsLogin", "Mobile" });
                    PublicFunction.AddOperation(1, string.Format("修改管理員"), string.Format("修改管理員=={0}==成功", model.Mobile));
                    if (EnterRepository.GetRepositoryEnter().SaveChange() > 0) {
                        return Json(new {
                            state = "success",
                            message = "修改管理員成功"
                        });
                    }
                    else {
                        PublicFunction.AddOperation(1, string.Format("修改管理員"), string.Format("修改管理員=={0}==失敗", model.Mobile));
                        EnterRepository.GetRepositoryEnter().SaveChange();
                        return Json(new {
                            state = "error",
                            message = "修改管理員失敗"
                        });
                    }
                }
            }
            else {
                return Json(new { state = "error", message = "信息不完整" });
            }
        }

        /// <summary>
        /// 更改管理員可登陸狀態
        /// </summary>
        /// <param name="id">管理員Id</param>
        /// <param name="state">管理員狀態</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdateState(int id = 0, int state = 0) {
            EnterRepository.GetRepositoryEnter().GetAdminRepository.EditEntity(new Model.Admin() { Id = id, IsLogin = (byte)state }, new string[] { "IsLogin" });
            PublicFunction.AddOperation(1, string.Format("修改管理員可登陸狀態"), string.Format("修改管理員可登陸狀態成功"));
            if (EnterRepository.GetRepositoryEnter().SaveChange() > 0) {
                return Json(new { state = "success", message = "修改管理員可登陸狀態成功" });
            }
            else {
                PublicFunction.AddOperation(1, string.Format("修改管理員可登陸狀態"), string.Format("修改管理員可登陸狀態失敗"));
                EnterRepository.GetRepositoryEnter().SaveChange();
                return Json(new { state = "error", message = "服務器泡妞去了" });
            }
        }
        /// <summary>
        /// 重置密碼
        /// </summary>
        /// <param name="id">管理員Id</param>
        /// <param name="newPassword">新密碼</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult RestPassword(int id, string newPassword) {
            Random rn = new Random();
            string salt = rn.Next(10000, 99999).ToString() + rn.Next(10000, 99999).ToString();
            EnterRepository.GetRepositoryEnter().GetAdminRepository.EditEntity(new Model.Admin() { Id = id, Password = MD5Helper.CreatePasswordMd5(newPassword, salt), Salt = salt }, new string[] { "Password", "Salt" });
            PublicFunction.AddOperation(1, string.Format("重置管理員密碼"), string.Format("重置管理員=={0}==密碼成功", id));
            if (EnterRepository.GetRepositoryEnter().SaveChange() > 0) {
                return Json(new { state = "success", message = "重置管理員密碼成功" });
            }
            else {
                PublicFunction.AddOperation(1, string.Format("重置管理員密碼"), string.Format("修改管理員=={0}==可登陸狀態失敗", id));
                EnterRepository.GetRepositoryEnter().SaveChange();
                return Json(new { state = "error", message = "服務器泡妞去了" });
            }
        }
        /// <summary>
        /// 刪除管理員
        /// </summary>
        /// <param name="id">管理員Id</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DeleteAdmin(int id = 0) {
            EnterRepository.GetRepositoryEnter().GetAdminRepository.DeleteEntity(new Model.Admin() { Id = id });
            PublicFunction.AddOperation(1, string.Format("刪除管理員"), string.Format("刪除管理員成功"));
            if (EnterRepository.GetRepositoryEnter().SaveChange() > 0) {
                return Json(new { state = "success", message = "刪除管理員成功" });
            }
            else {
                PublicFunction.AddOperation(1, string.Format("刪除管理員"), string.Format("刪除管理員失敗"));
                EnterRepository.GetRepositoryEnter().SaveChange();
                return Json(new { state = "error", message = "服務器泡妞去了" });
            }
        }
    }
}
View Code

頁面代碼

@section Header{
    <style type="text/css">
        /*加載動態圖片*/
        .dataTables_processing {
            position: absolute;
            top: 50%;
            left: 50%;
            width: 100%;
            height: 40px;
            margin-left: -50%;
            margin-top: -25px;
            padding-top: 20px;
            text-align: center;
            font-size: 1.2em;
            /*background-color: white;*/
        }
    </style>
}

<div class="main-content">
    <div class="breadcrumbs" id="breadcrumbs">
        <script type="text/javascript">
            try { ace.settings.check('breadcrumbs', 'fixed') } catch (e) { }
        </script>

        <ul class="breadcrumb">
            <li>
                <i class="icon-home home-icon"></i>
                <a href="/Admin/Home">首頁</a>
            </li>
            <li>
                <a href="/Admin/Admin/AdminList">管理員列表</a>
            </li>
            <li class="active">管理員列表</li>
        </ul><!-- .breadcrumb -->
        <!-- #nav-search -->
    </div>
    <div class="page-content">
        <div class="row">
            <div class="col-xs-12">
                <!-- PAGE CONTENT BEGINS -->

                <div class="row">
                    <div class="col-xs-12">
                        <div class="table-header">
                            管理員列表查看
                        </div>
                        <div class="hidden" id="hidden_filter">
                            @* 把需要搜索的條件放到hidden里面,在table格式化完成的時候直接調用$.html()賦值,免去了在js拼接標簽的麻煩 *@
                            <div style="float:left;">
                                <label class="AddRole">
                                    <a id="AddNewRole" class="btn btn-xs btn-primary" data-toggle="modal" href="" onclick="showAddNewAdmin()" title="添加新管理員">
                                        <i class="icon-plus-sign bigger-130"></i>
                                        添加新管理員
                                    </a>
                                </label>
                                <label class="SearchRole">
                                    <label>手機號碼:</label>
                                    <label>
                                        @Html.TextBox("Mobile_Search", "", new { @class = "form-control input-small", style = "width:150px", placeholder = "請輸入手機號碼" })
                                    </label>
                                    <label>選擇角色: </label>
                                    <label>
                                        <select id="Authory_Search">
                                            @foreach (var item in ViewBag.RoleSelectItem) {
                                                <option value="@item.Value">@item.Text</option>
                                            }
                                        </select>
                                    </label>
                                    <label>
                                        <a href="javascript:Search();" class="btn btn-xs btn-success">
                                            <i class="icon-search bigger-130"></i>
                                            搜索
                                        </a>
                                        <i class="fa fa-search"></i>
                                    </label>
                                </label>
                            </div>
                        </div>
                        <div class="table-responsive dataTables_wrapper">
                            <table id="sample-table-2" class="table table-striped table-bordered table-hover">
                                <thead>
                                    <tr>
                                        <th class="center sorting_disabled" role="columnheader" rowspan="1" colspan="1" aria-label="" style="width: 58px;">
                                            <label>
                                                <input type="checkbox" class="ace">
                                                <span class="lbl"></span>
                                            </label>
                                        </th>
                                        <th>手機號碼</th>
                                        <th>用戶名</th>
                                        <th>郵箱</th>
                                        <th>角色名稱</th>
                                        <th>上次登錄時間</th>
                                        <th>是否可登陸</th>
                                        <th>創建時間</th>
                                        <th style="width: 120px;">
                                            操作
                                        </th>
                                    </tr>
                                </thead>
                            </table>
                        </div>
                    </div>
                </div>
                <!-- PAGE CONTENT ENDS -->
            </div><!-- /.col -->
        </div><!-- /.row -->
    </div><!-- /.page-content -->
</div>
<div class="modal fade" id="ShowAdd" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    @RenderPage("/Areas/Admin/Views/Admin/DisplayTemplates/AdminTemp.cshtml", new { SelectItem = ViewBag.RoleSelectItem })
</div>
@section script{
    <script src="/Content/assets/js/jquery.dataTables.min.js"></script>
    <script src="/Content/assets/js/jquery.dataTables.bootstrap.js"></script>
    <script src="/Content/assets/js/bootbox.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

    <script type="text/javascript">
        var isSearch = false;
        $(function () {
            var objTable = $("#sample-table-2").dataTable({
                aoColumns: [
                    { "sClass": "center", "mDataProp": "Id", "bSortable": false },
                    { "sClass": "center", "mDataProp": "Mobile", "bSortable": false },
                    { "sClass": "center", "mDataProp": "AdminName", "bSortable": false },
                    { "sClass": "center", "mDataProp": "Email", "bSortable": false },
                    { "sClass": "center", "mDataProp": "Name", "bSortable": false },
                    { "sClass": "center", "mDataProp": "LastLoginTime", "bSortable": false },
                    { "sClass": "center", "mDataProp": "IsLogin", "bSortable": false },
                    { "mDataProp": "CreateTime", "sClass": "center", "bSortable": true, "asSorting": ["asc", "desc"] },
                    {
                        "sClass": "center",
                        "mDataProp": "Id",
                        "bSortable": false
                    }
                ],
                "bServerSide": true,//分頁,取數據等等的都放到服務端去
                "bProcessing": true,//載入數據的時候是否顯示“載入中”
                "aLengthMenu": [20, 30, 50, 100],
                "bLengthChange": true, //改變每頁顯示數據數量
                //"bFilter": false, //過濾功能
                "iDisplayStart": 0,
                "iDisplayLength": 20,//首次加載的數據條數
                "bStorable": true,//排序操作在服務端進行,所以可以關了。
                "sAjaxSource": "/Admin/Admin/AdminList",
                "fnServerParams": function (aoData, bStorable) {
                },
                /*如果加上下面這段內容,則使用post方式傳遞數據*/
                "fnServerData": function (sSource, aoData, fnCallback, bStorable) {
                    var paramList = {
                        "sEcho": 0,
                        "iDisplayLength": 0,
                        "iDisplayStart": 0,
                        "isDesc": bStorable.aaSorting[0][1] == "desc" ? true : false,
                        "RoleId": isSearch ==true?$("#Authory_Search").val() : -1,
                        "Mobile": isSearch == true?$("#Mobile_Search").val() : ""
                    };
                    if (bStorable.aaSorting[0][0] == 0) {
                        paramList.isDesc = true;
                    }
                    for (var i = 0; i < aoData.length; i++) {
                        if (aoData[i].name == "iDisplayStart") {
                            paramList.iDisplayStart = aoData[i].value;
                        } else if (aoData[i].name == "iDisplayLength") {
                            paramList.iDisplayLength = aoData[i].value;
                        } else if (aoData[i].name == "sEcho") {
                            paramList.sEcho = aoData[i].value;
                        }
                    }
                    $.ajax({
                        "dataType": 'json',
                        "type": "POST",
                        "url": sSource,
                        "data": paramList,
                        "success": function (resp) {
                            fnCallback(resp); //服務器端返回的對象的returnObject部分是要求的格式
                        }
                    });
                },
                "oLanguage": {
                    "sSearch": "搜索",
                    "sLengthMenu": "每頁顯示 _MENU_ 條記錄",
                    "sZeroRecords": "抱歉, 沒有找到",
                    "sInfo": "從 _START_ 到 _END_ 共 _TOTAL_ 條數據",
                    "sInfoEmpty": "沒有數據",
                    "sInfoFiltered": "(從 _MAX_ 條數據中檢索)",
                    "oPaginate": {
                        "sFirst": "首頁",
                        "sPrevious": "前一頁",
                        "sNext": "后一頁",
                        "sLast": "尾頁"
                    },
                    "sZeroRecords": "沒有檢索到數據",
                    "sProcessing": "<img src='/Content/assets/images/loading.gif' />"
                },
                "fnRowCallback": function (nRow, aData, iDisplayIndex) {  /* 用來改寫指定行的樣式 */
                    $('td:eq(0)', nRow).html("<label><input type=\"checkbox\" class=\"ace\" value=\"" + aData.Id + "\"><span class=\"lbl\"></span></label>");
                    $('td:eq(5)', nRow).html(GetDateYMR(aData.LastLoginTime));
                    $('td:eq(7)', nRow).html(GetDateYMR(aData.CreateTime));
                    var html = "<div class=\"visible-md visible-lg hidden-sm hidden-xs action-buttons\">";
                    // html += "<a class=\"blue\" href=\"#\"><i class=\"icon-zoom-in bigger-130\"></i></a>";//查看按鈕
                    html += "<a class=\"green LookRole\" href=\"javascript:UpdateObj('" + aData.Id + "')\" title=\"編輯\"><i class=\"icon-pencil bigger-130\"></i></a>";//編輯
                    if (aData.IsLogin == 1) {
                        $('td:eq(6)', nRow).html("<i class=\"icon-ok green bigger-120\"></i>");
                        html += "<a class=\"red UpdateRole\" href=\"javascript:CanLogin('" + aData.Id + "',0)\" title=\"不能登錄\"><i class=\"icon-remove bigger-130\"></i></a>";//刪除
                    }
                    else {
                        $('td:eq(6)', nRow).html("<i class=\"icon-remove red bigger-120\"></i>");
                        html += "<a class=\"green UpdateRole\" href=\"javascript:CanLogin('" + aData.Id + "',1)\" title=\"可登陸\"><i class=\"icon-ok bigger-130\"></i></a>";
                    }
                    html += "<a class=\"red UpdateRole\" href=\"javascript:ShowPrompt('" + aData.Id + "')\" title=\"重置密碼\"><i class=\"icon-refresh bigger-130\"></i></a>";
                    html += "<a class=\"red DeleteRole\" href=\"javascript:DeleteObj('" + aData.Id + "')\" title=\"刪除管理員\"><i class=\"icon-trash bigger-130\"></i></a>";//刪除
                    html += "</div>";
                    $('td:eq(8)', nRow).html(html);
                    return nRow;
                }
            });
            //下面的代碼主要是將下拉框的位置已到右邊去
            $("#sample-table-2_length").parents().first().removeClass("col-sm-6").addClass("col-sm-3");
            $("#sample-table-2_length").parents().first().css("float", "right");
            $("#sample-table-2_filter").parents().first().removeClass("col-sm-6").addClass("col-sm-8");
            $("#sample-table-2_filter").parents().first().css("float", "left");
            $("#sample-table-2_length").css("float", "right");
            $("#sample-table-2_filter").html($("#hidden_filter").html());
            $("#hidden_filter").remove();
        })
        //搜索
        function Search() {
            isSearch = true;
            $("#sample-table-2").dataTable().fnDraw();//點搜索重新繪制table。
        }
        function showAddNewAdmin() {
            $("#Id").val(0);
            $('#ShowAdd').modal();
        }
        function UpdateObj(id) {
            $.ajax({
                type: "post",
                data: { id: id },
                url: "/Admin/Admin/GetAdminInfo",
                success: function (result) {
                    if (result.state == "success") {
                        $("#Id").val(id);
                        $("#Mobile").val(result.result.Mobile);
                        $("#AuthoryId option[value=" + result.result.AuthoryId + "]").attr("selected", "selected");
                        if (result.result.IsLogin == 1) {
                            $("input[name='IsLogin']").eq(0).removeAttr("checked");
                            $("input[name='IsLogin']").eq(1).attr("checked", "checked");
                        }
                        else {
                            $("input[name='IsLogin']").eq(0).attr("checked", "checked");
                            $("input[name='IsLogin']").eq(1).removeAttr("checked");
                        }
                        $('#ShowAdd').modal();
                    } else {
                        bootbox.alert({
                            buttons: {
                                ok: {
                                    label: '我知道了',
                                    className: 'btn btn-primary'
                                }
                            }, callback: function () {
                            },
                            message: result.message
                        });
                    }
                }
            })
        }
        $("#AddRoleForm").submit(function () {
            if ($("#AddRoleForm").valid()) {
                var url = "/Admin/Admin/AddAdmin";
                if ($("#Id").val() > 0) {
                    url = "/Admin/Admin/UpdateAdmin";
                }
                $.ajax({
                    type: "post",
                    data: $("#AddRoleForm").serialize(),
                    url: url,
                    success: function (result) {
                        if (result.state == "success") {
                            $('#ShowAdd').modal('hide');//關閉模態框
                            document.getElementById("AddRoleForm").reset();//清空表單
                            bootbox.alert({
                                buttons: {
                                    ok: {
                                        label: '我知道了',
                                        className: 'btn btn-primary'
                                    }
                                }, callback: function () {
                                    $("#sample-table-2").dataTable().fnDraw();//點搜索重新繪制table。
                                },
                                message: result.message
                            });
                        } else {
                            bootbox.alert({
                                buttons: {
                                    ok: {
                                        label: '我知道了',
                                        className: 'btn btn-primary'
                                    }
                                }, callback: function () {
                                },
                                message: result.message
                            });
                        }
                    }
                })
                return false;
            }
            else {
                return false;
            }
        })
        function CanLogin(id, state) {
            bootbox.confirm({
                buttons: {
                    confirm: {
                        label: '確定',
                        className: 'btn-primary'
                    },
                    cancel: {
                        label: '取消',
                        className: 'btn-default'
                    }
                },
                message: state == 0 ? "確定禁止該管理員登錄嗎" : "確定恢復該管理員登錄嗎",
                callback: function (result) {
                    if (result) {
                        UpdateState(id, state)
                    }
                }
            });
        }
        function UpdateState(id, state) {
            $.ajax({
                type: "post",
                data: { id: id, state: state },
                url: "/Admin/Admin/UpdateState",
                success: function (result) {
                    if (result.state == "success") {
                        bootbox.alert({
                            buttons: {
                                ok: {
                                    label: '我知道了',
                                    className: 'btn btn-primary'
                                }
                            }, callback: function () {
                                $("#sample-table-2").dataTable().fnDraw();//點搜索重新繪制table。
                            },
                            message: result.message
                        });
                    } else {
                        bootbox.alert({
                            buttons: {
                                ok: {
                                    label: '我知道了',
                                    className: 'btn btn-primary'
                                }
                            }, callback: function () {
                            },
                            message: result.message
                        });
                    }
                }
            })
        }

        function DeleteObj(id) {
            bootbox.confirm({
                buttons: {
                    confirm: {
                        label: '確定',
                        className: 'btn-primary'
                    },
                    cancel: {
                        label: '取消',
                        className: 'btn-default'
                    }
                },
                message: "確定要徹底刪除該角色嗎?",
                callback: function (result) {
                    if (result) {
                        $.ajax({
                            type: "post",
                            data: { id: id },
                            url: "/Admin/Admin/DeleteAdmin",
                            success: function (result) {
                                if (result.state == "success") {
                                    bootbox.alert({
                                        buttons: {
                                            ok: {
                                                label: '我知道了',
                                                className: 'btn btn-primary'
                                            }
                                        }, callback: function () {
                                            $("#sample-table-2").dataTable().fnDraw();//點搜索重新繪制table。
                                        },
                                        message: result.message
                                    });
                                } else {
                                    bootbox.alert({
                                        buttons: {
                                            ok: {
                                                label: '我知道了',
                                                className: 'btn btn-primary'
                                            }
                                        }, callback: function () {
                                        },
                                        message: result.message
                                    });
                                }
                            }
                        })
                    }
                }
            });
        }
        function RestPassword(id,password) {
            $.ajax({
                type: "post",
                data: { id: id, newPassword: password },
                url: "/Admin/Admin/RestPassword",
                success: function (result) {
                    if (result.state == "success") {
                        bootbox.alert({
                            buttons: {
                                ok: {
                                    label: '我知道了',
                                    className: 'btn btn-primary'
                                }
                            }, callback: function () {
                                $("#sample-table-2").dataTable().fnDraw();//點搜索重新繪制table。
                            },
                            message: result.message
                        });
                    } else {
                        bootbox.alert({
                            buttons: {
                                ok: {
                                    label: '我知道了',
                                    className: 'btn btn-primary'
                                }
                            }, callback: function () {
                            },
                            message: result.message
                        });
                    }
                }
            })
        }
        function ShowPrompt(id) {
            bootbox.prompt("請輸入新的密碼", function (result) {
                if (result == null) {

                }
                else if (result == "" || result.length < 6) {
                    bootbox.alert({
                        buttons: {
                            ok: {
                                label: '我知道了',
                                className: 'btn btn-primary'
                            }
                        }, callback: function () {
                            ShowPrompt(id);
                        },
                        message: '密碼長度不能少於6位'
                    });
                    
                } else {
                    RestPassword(id, result)
                }
            });
        }
    </script>
}
@model AuthorDesign.Web.Areas.Admin.Models.AdminModel

<div class="main-content col-xs-8" style="margin-top: 70px; margin-left: 15%;">
    <div class="page-content">
        <div class="row">
            <section>
                <div class="page-header">
                    <h1>
                        管理員管理
                        <small>
                            <i class="icon-double-angle-right"></i>
                            <span id="ShowText">管理員編輯</span>
                        </small>
                    </h1>
                </div>
                <div class="col-lg-10 col-lg-offset-2">
                    <form id="AddRoleForm" class="form-horizontal">
                        <fieldset>
                            @Html.HiddenFor(m => m.Id)
                            <div class="form-group">
                                <label class="col-lg-3 control-label">手機號碼<span style="color:red;">*</span>:</label>
                                <div class="col-lg-7" style="float:left;">
                                    @Html.TextBoxFor(m => m.Mobile, new { @class = "col-sm-8" })
                                    @Html.ValidationMessageFor(m => m.Mobile)
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-3 control-label">角色:</label>
                                <div class="col-lg-7">
                                    <select id="AuthoryId" name="AuthoryId">
                                        @foreach (var item in ViewBag.RoleSelectItem) {
                                            <option value="@item.Value">@item.Text</option>
                                        }
                                    </select>
                                    @*@Html.DropDownListFor(m => m.AuthoryId, PageData["SelectItem"] as IEnumerable<SelectListItem>)*@
                                    @Html.ValidationMessageFor(m => m.AuthoryId)
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-3 control-label">是否可登錄</label>
                                <div class="col-lg-7">
                                    <label>
                                        <input name="IsLogin" type="radio" class="ace" value="0" checked="checked" />
                                        <span class="lbl">不可登錄</span>
                                    </label>
                                    <label>
                                        <input name="IsLogin" type="radio" class="ace" value="1" />
                                        <span class="lbl">可登陸</span>
                                    </label>
                                </div>
                            </div>
                        </fieldset>
                        <div class="form-group">
                            <div class="col-lg-9 col-lg-offset-3">
                                <button class="btn btn-primary UpdateRole" type="submit">
                                    <i class="icon-ok bigger-110"></i>
                                    保存
                                </button>
                                <button class="btn" type="reset" data-dismiss="modal">
                                    <i class="icon-undo bigger-110"></i>
                                    取消
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </section>
            <!-- /.row -->
        </div>
    </div>
    <!-- /.page-content -->
</div>
View Code

頁面效果

用戶和頁面按鈕就這樣完成了,最后,如果誰有稍微好弄一點的樹形結構的樣式,麻煩推薦我下,我打算在頁面那邊使用。

百度源碼下載地址


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM