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


接下來先做角色這一板塊的(增刪改查),首先要新建一個Role控制器,在添加一個RoleList的視圖。表格打算采用的是bootstrap的表格。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

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

        public ActionResult RoleList()
        {
            return View();
        }

    }
}
View Code

在當我做查詢的時候返現角色少了個排序,也可以說是角色的等級吧,也可以就是用來排序用的。那么老方法先在AuthorDesign.Model.Authory這個類下面新增一個屬性

        /// <summary>
        /// 排序數字
        /// </summary>
        public int OrderNum { get; set; }
View Code

然在打開控制台選擇DAL然后輸入add-migration AddAuthoryOrderNum 完成之后再次輸入update-database即可。

然后在Model下建立一個ParamModel,這是專門用來接收分頁信息的。

#region 分頁基類
    /// <summary>
    /// 分頁基類
    /// </summary>
    public class ParamModel
    {
        /// <summary>
        /// DataTable請求服務器端次數
        /// </summary>       
        public string sEcho { get; set; }

        /// <summary>
        /// 每頁顯示的數量
        /// </summary>
        public int iDisplayLength { get; set; }

        /// <summary>
        /// 分頁時每頁跨度數量
        /// </summary>
        public int iDisplayStart { get; set; }
    }
    #endregion
View Code

然后在建立一個RoleParamModel,繼承下ParamModel,

#region 角色分頁
    /// <summary>
    /// 角色分頁
    /// </summary>
    public class RoleParamModel : ParamModel
    {
        /// <summary>
        /// 是否根據排序字段進行倒序排列
        /// </summary>
        public bool IsDesc { get; set; }
    }
    #endregion
View Code

接下在AuthoryRepository這個下面寫一個獲取權限分頁的方法

        /// <summary>
        /// 獲取角色分頁列表
        /// </summary>
        /// <param name="startNum">起始數字</param>
        /// <param name="pageSize">頁長</param>
        /// <param name="isDesc">是否倒序排列</param>
        /// <param name="rowCount">總頁數</param>
        /// <returns>角色分頁列表</returns>
        public IQueryable<Authory> LoadPageList(int startNum, int pageSize, bool isDesc, out int rowCount) {
            rowCount = 0;
            var result = from p in db.Set<Authory>()
                         select p;
            if (isDesc) {
                result = result.OrderByDescending(m => m.OrderNum);
            }
            else {
                result = result.OrderBy(m => m.OrderNum);
            }
            rowCount = result.Count();
            return result.Skip(startNum).Take(pageSize);
        }
View Code

我可能實現的方法寫的不好,如果有什么地方需要改進的麻煩你們告訴我下。

然后再去IAuthoryRepository這個接口上定義下規范

        /// <summary>
        /// 獲取角色分頁列表
        /// </summary>
        /// <param name="startNum">起始數字</param>
        /// <param name="pageSize">頁長</param>
        /// <param name="isDesc">是否倒序排列</param>
        /// <param name="rowCount">總頁數</param>
        /// <returns>角色分頁列表</returns>
        IQueryable<Authory> LoadPageList(int startNum, int pageSize, bool isDesc, out int rowCount);
View Code

接下來就是前台的調用了,在Role控制下添加一個返回JsonResult的方法

        public ActionResult RoleList()
        {
            return View();
        }

        [HttpPost]
        public JsonResult RoleList(Models.RoleParamModel model) {
            int rowCount = 0;
            var result = EnterRepository.GetRepositoryEnter().GetAuthoryRepository.LoadPageList(model.iDisplayStart, model.iDisplayLength, model.IsDesc, out rowCount);
            return Json(new {
                sEcho = model.sEcho,
                iTotalRecords = rowCount,
                iTotalDisplayRecords = rowCount,
                aaData = result
            }, JsonRequestBehavior.AllowGet);
        }
View Code

先對RoleParamModel這個類解釋下,這類里面有四個屬性,分別是

        /// <summary>
        /// DataTable請求服務器端次數
        /// </summary>       
        public string sEcho { get; set; }

        /// <summary>
        /// 每頁顯示的數量
        /// </summary>
        public int iDisplayLength { get; set; }

        /// <summary>
        /// 分頁時每頁跨度數量
        /// </summary>
        public int iDisplayStart { get; set; }
        /// <summary>
        /// 是否根據排序字段進行倒序排列
        /// </summary>
        public bool IsDesc { get; set; }
sEcho是jquery.dataTables這個插件在與后台進行交互的時候會自動傳過來的(aData里面可以獲取到的);iDisplayLength與iDisplayStart也是同樣可以獲取的到的,然后IsDesc這個字段用來表示用戶是選擇按照排序字段正序排序還是倒序排序用的。下面給上我的前台代碼:
@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/Role/RoleList">角色列表</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="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>

@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 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": "Intro", "bSortable": false },
                    { "sClass": "center", "mDataProp": "State", "bSortable": false },
                    { "mDataProp": "OrderNum", "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/Role/RoleList",
                "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>");
                    return nRow;
                }
            });
            $("#sample-table-2_filter").html("");//移除自帶的搜索
        })
    </script>
}
View Code

前台代碼主要是jquery.dataTables的使用,我對jquery.dataTables獲取那個特定字段的排序還不是很清楚,只能通過遍歷下bStorable里面的內容去獲取。下面稍微解釋下前台代碼

 "sAjaxSource": "/Admin/Role/RoleList",這個主要定義下服務請求的路徑。aoColumns:這下面主要是設置列的信息與樣式用的。

"fnRowCallback": function (nRow, aData, iDisplayIndex) { /* 用來改寫指定行的樣式 */
$('td:eq(0)', nRow).html("<label><input type=\"checkbox\" class=\"ace\" value=\"" + aData.Id + "\"><span class=\"lbl\"></span></label>");
return nRow;
}
View Code

這代碼主要用來改寫指定行的樣式,比如第0行就把他改為了選擇框的樣式。

這里是jquery-datatables的一些信息,可以自己去看下。$("#sample-table-2_filter").html("");//移除自帶的搜索  這段代碼主要是為了移除掉原來他自帶的搜索框,你可以先去掉看下效果然后再加上。下面放上頁面的顯示效果

那么做了列表之后接下來就是對權限的增加與修改了。下面是Role控制器的全部代碼,里面包括了修改,刪除,增加,更改角色狀態

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 RoleController : Controller {
        //
        // GET: /Admin/Role/

        public ActionResult RoleList() {
            return View();
        }

        [HttpPost]
        public JsonResult RoleList(Models.RoleParamModel model) {
            int rowCount = 0;
            var result = EnterRepository.GetRepositoryEnter().GetAuthoryRepository.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 GetRoleInfo(int id = 0) {
            var result = EnterRepository.GetRepositoryEnter().GetAuthoryRepository.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 AddRole(Models.RoleModel model) {
            if (ModelState.IsValid) {
                IDAL.IAuthoryRepository authoryRepository = EnterRepository.GetRepositoryEnter().GetAuthoryRepository;
                //判斷權限名稱是否已存在
                var result = authoryRepository.LoadEntities(m => m.Name == model.Name.Trim()).FirstOrDefault();
                if (result == null) {
                    authoryRepository.AddEntity(new Model.Authory() {
                        Intro = model.Intro,
                        Name = model.Name,
                        OrderNum = model.OrderNum,
                        State = model.State
                    });
                    //添加下操作記錄
                    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 UpdateRole(Models.RoleModel model) {
            if (ModelState.IsValid && model.Id > 0) {
                IDAL.IAuthoryRepository authoryRepository = EnterRepository.GetRepositoryEnter().GetAuthoryRepository;
                //判斷權限名稱是否已存在
                var result = authoryRepository.LoadEntities(m => m.Name == model.Name.Trim()).FirstOrDefault();
                if (result != null && result.Id != model.Id) {
                    return Json(new {
                        state = "error",
                        message = "角色名稱已經存在了"
                    });
                }
                else {
                    Model.Authory authory = new Model.Authory() {
                        Intro = model.Intro,
                        Name = model.Name,
                        OrderNum = model.OrderNum,
                        State = model.State,
                        Id = model.Id
                    };
                    EnterRepository.GetRepositoryEnter().GetAuthoryRepository.Get(m => m.Id == model.Id);
                    EnterRepository.GetRepositoryEnter().GetAuthoryRepository.EditEntity(authory, new string[] { "Intro", "Name", "OrderNum", "State" });
                    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().GetAuthoryRepository.EditEntity(new Model.Authory() { Id = id, State = (byte)state }, new string[] { "State" });
            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>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DeleteRole(int id = 0) {
            EnterRepository.GetRepositoryEnter().GetAuthoryRepository.DeleteEntity(new Model.Authory() { 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

在做修改的時候我碰到了Attaching an entity of type 'AuthorDesign.Model.Authory' failed because another entity of the same t這個問題,大概意思就是說你在修改的時候context還包有一個相同主鍵值的,隨意不能進行修改。修改方法參照這個網址http://www.cnblogs.com/scy251147/p/3688844.html,這里說的很詳細。順便添上我RoleList的整個頁面代碼

@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/Role/RoleList">角色列表</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 class="AddRole" 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>
                            </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/Role/DisplayTemplates/RoleTemp.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": "Intro", "bSortable": false },
                    { "sClass": "center", "mDataProp": "State", "bSortable": false },
                    { "mDataProp": "OrderNum", "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/Role/RoleList",
                "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=\"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.State == 0) {
                        $('td:eq(4)', nRow).html("正常狀態");
                        html += "<a class=\"red UpdateRole\" href=\"javascript:CanShow('" + aData.Id + "',1)\" title=\"假刪除\"><i class=\"icon-remove bigger-130\"></i></a>";//刪除
                    }
                    else {
                        $('td:eq(4)', nRow).html("假刪除");
                        html += "<a class=\"green UpdateRole\" href=\"javascript:CanShow('" + aData.Id + "',0)\" title=\"恢復正常\"><i class=\"icon-ok 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(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").html();
        })

        function showAddNewAdmin() {
            $("#Id").val(0);
            $('#ShowAdd').modal();
        }
        function UpdateObj(id) {
            $.ajax({
                type: "post",
                data: { id: id },
                url: "/Admin/Role/GetRoleInfo",
                success: function (result) {
                    if (result.state == "success") {
                        $("#Id").val(id);
                        $("#Name").val(result.result.Name);
                        $("#Intro").val(result.result.Intro);
                        $("#OrderNum").val(result.result.OrderNum);
                        if (result.result.State == 1) {
                            $("input[name='State']").eq(0).removeAttr("checked");
                            $("input[name='State']").eq(1).attr("checked", "checked");
                        }
                        else {
                            $("input[name='State']").eq(0).attr("checked", "checked");
                            $("input[name='State']").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/Role/AddRole";
                if ($("#Id").val() > 0) {
                    url = "/Admin/Role/UpdateRole";
                }
                $.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/Role/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/Role/DeleteRole",
                            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>
}
View Code
@model AuthorDesign.Web.Areas.Admin.Models.RoleModel

<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">角色簡介:</label>
                                <div class="col-lg-7">
                                    @Html.TextBoxFor(m => m.Intro, new { @class = "col-sm-8" })
                                    @Html.ValidationMessageFor(m => m.Intro)
                                </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.OrderNum, new { @class = "col-sm-8" })
                                    @Html.ValidationMessageFor(m => m.OrderNum)
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-3 control-label">角色狀態</label>
                                <div class="col-lg-7">
                                    <label>
                                        <input name="State" type="radio" class="ace" value="0" checked="checked" />
                                        <span class="lbl">正常</span>
                                    </label>
                                    <label>
                                        <input name="State" 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

頁面代碼上需要注意的是我在添加修改和刪除這里分別加上了AddRole和UpdateRole和DeleteRole,這是為了方便下面可以使用。

在做修改的時候,ajax需要把每個字段都要重新賦值一邊給文本框,問下你們有沒有簡單的方法,除了用Angularjs和KO框架之外。知道麻煩告訴我下啊。

百度源碼下載地址


免責聲明!

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



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