ASP.NET MVC4.0+EF+LINQ+bui+bootstrap+网站+角色权限管理系统(3)

接下来完成用户、角色的增删查改,以及用户角色、权限的设置

对用户表、角色表做了一些扩展如下【可以更加自己需要增减字段】

相应的M_UserProfile.cs、M_Roles.cs进行扩展

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace MVCSystem.Web.Models
{
    
    [Table("UserProfile")]
    public class M_UserProfile
    {
        [Key]
        [Display(Name = "ID")]
        public int UserId { get; set; }

        [Display(Name = "用户名")]
        [StringLength(250)]
        public string UserName { get; set; }

        [Display(Name = "邮件地址")]
        [StringLength(250)]
        public string Email { get; set; }

        [Display(Name = "真实姓名")]
        [StringLength(250)]
        public string RealName { get; set; }

        [Display(Name = "状态")]
        public int State { get; set; }
    }
}
View Code
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace MVCSystem.Web.Models
{ [Table("webpages_Roles")]
    public class M_Roles
    {


             public M_Roles()
            {
                T_Members = new List<M_Membership>();
                T_PermissionsInRoles = new List<M_PermissionsInRoles>();
            }

            [Key]
            [Display(Name = "ID")]
            public int RoleId { get; set; }

            [Display(Name = "名称")]
            [StringLength(256)]
            public string RoleName { get; set; }

            [Display(Name = "状态")]
            public int State { get; set; }
            public ICollection<M_Membership> T_Members { get; set; }

            [ForeignKey("RoleId")]
            public ICollection<M_PermissionsInRoles> T_PermissionsInRoles { set; get; }
       
    }
}
View Code

接下来编写控制器以及视图的代码

UsersController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using MVCSystem.Web.Common;
using MVCSystem.Web.Filters;
using MVCSystem.Web.Models;
using WebMatrix.WebData;

namespace MVCSystem.Web.Areas.Admin.Controllers
{
     [InitializeSimpleMembership]
    public class UsersController : BaseController
    {
        //
        // GET: /Admin/Users/
         /// <summary>
         /// 获取数据列表
         /// </summary>
         /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult GetList(GridPager pager)
        {
            var aList = db.DB_UserProfiles.ToList();
            aList = aList.OrderByDescending(a => a.UserId).ToList();
              var json = new
            {
                results = aList.Count,
                rows = aList.Select(a => new
                        {
                            UserId = a.UserId,
                            UserName = a.UserName,
                            UserEmail = a.Email,
                            RealName = a.RealName,
                            State = (a.State==1)?"启用":"禁用",
                            UserRole=getRoleName(a.UserId),
                            CZ = "<a href='javascript:;' onclick='SetRole(" + a.UserId + ")' id='SetRole'>角色设置</a><a href='/Admin/Users/UserProfilesEdit/" + a.UserId + "' id='Edit'>编辑</a><a href='javascript:;' onclick='DeleteShow(" + a.UserId + ")' id='Delete'>删除</a>"

                        }).Skip((pager.pageIndex) * pager.limit).Take(pager.limit).ToArray()
            };
            return Json(json, JsonRequestBehavior.AllowGet);
        }
         private string getRoleName(int UsId)
        {
            var gg = (from a in db.DB_UsersInRoles
                      join b in db.DB_Roles
                       on a.RoleId equals b.RoleId
                      group new { a, b } by new { a.UserId, b.RoleName } into kk
                      select new
                      {
                          userId = kk.Key.UserId,
                          roleName = kk.Key.RoleName
                      }).ToList();
            var getRoleNameStr = String.Join("", gg.Where(d => d.userId == UsId).Select(e => e.roleName).ToArray());
            return getRoleNameStr;
        }

         /// <summary>
         /// 删除数据操作
         /// </summary>
         /// <param name="id"></param>
         /// <returns></returns>
         [HttpPost]
         public JsonResult UserProfilesDelete(int id)
         {
             if (id > 0)
             {
                 var aList = db.DB_UserProfiles.Find(id);
                 db.DB_UserProfiles.Remove(aList);
                 db.SaveChanges();
                 return Json(1, JsonRequestBehavior.AllowGet);
             }
             else
             {
                 return Json(0, JsonRequestBehavior.AllowGet);
             }
         }
         /// <summary>
         /// 编辑数据操作
         /// </summary>
         /// <param name="id"></param>
         /// <returns></returns>
         public ActionResult UserProfilesEdit(int id)
         {
             var aList = db.DB_UserProfiles.Find(id);
             return View(aList);
         }
         [HttpPost]
         public ActionResult UserProfilesEdit(int id, FormCollection collection)
         {
             var aList = db.DB_UserProfiles.Find(id);
             if (TryUpdateModel(aList))
             {
                 aList.State =(collection.Get("State")=="1")?1:0;
                 db.SaveChanges();
                 return Content("<script>alert('编辑成功!');window.location = '/admin/Users/';</script>");

             }
             else
             {
                 return View(aList);
             }
         }

         /// <summary>
         /// 添加数据操作
         /// </summary>
         /// <returns></returns>
         public ActionResult UserProfilesAdd()
         {
             ViewBag.roleList = GetRoleSelectList();
             return View();
         }

         [HttpPost]
         public ActionResult UserProfilesAdd(FormCollection collection, string[] roles)
         {
             if (ModelState.IsValid)
             {
                 string userName = collection.Get("UserName");
                 string password = collection.Get("Password");
                 string email = collection.Get("Email");
                 string realName = collection.Get("RealName");
                 int state = (collection.Get("State")=="1")?1:0;
                 if (db.DB_UserProfiles.SingleOrDefault(e => e.UserName == userName) == null)
                 {
                     WebSecurity.CreateUserAndAccount(userName, password);
                     if (roles != null)
                     {
                         foreach (var roleName in roles)
                         {
                             Roles.AddUserToRole(userName, roleName);
                         }
                     }

                     M_UserProfile user = db.DB_UserProfiles.Single(e => e.UserName == userName);
                     user.Email = email;
                     user.State = state;
                     user.RealName = realName;
                     db.SaveChanges();

                     return Content("<script>alert('添加成功!');window.location = '/admin/Users/';</script>");
                 }
                 else
                 {

                     ViewBag.roleList = GetRoleSelectList();
                     ViewBag.MrrTip = "用户名已存在!";

                 }
             }

             return View();
         }
         /// <summary>
         /// 角色设置
         /// </summary>
         /// <param name="id"></param>
         /// <returns></returns>
         public ActionResult UserProfilesSetRole(int id)
         {

             var uList = db.DB_UserProfiles.Find(id);
             var roleU = db.DB_UsersInRoles.Where(u => u.UserId == id).ToList();
             var roleR = db.DB_Roles.ToList();
             var str = new StringBuilder();
             str.Append("<div class='checkboxlist'>");
             foreach (var rs in db.DB_Roles)
             {
                 str.Append("<span style='padding-left:10px;'>" + rs.RoleName + "</span>");

                 string strCK = "";
                 foreach (var ru in roleU)
                 {
                     if (ru.RoleId == rs.RoleId)
                     {
                         strCK = "checked='checked'";
                     }
                 }
                 str.Append("<input type='checkbox'" + strCK + " value='" + rs.RoleName + "' name='roles'/>");
             }
             str.Append("</div>");
             ViewBag.roleList = str;
             return View(uList);
         }

         private string GetRoleSelectList()
         {
             var str = new StringBuilder();
             str.Append("<div class='checkboxlist'>");
             foreach (var role in db.DB_Roles)
             {
                 str.Append("<span style='padding-left:10px;'>" + role.RoleName + "</span>");
                 str.Append("<input type='checkbox' value='" + role.RoleName + "' name='roles' />");

             }
             str.Append("</div>");

             return str.ToString();
         }
         /// <summary>
         /// 更改角色
         /// </summary>
         /// <param name="id"></param>
         /// <returns></returns>
         public JsonResult SetRole(string id)
         {
             int userId = int.Parse(id.Split(new string[] { "," }, StringSplitOptions.None)[0]);
             string roleName = id.Split(new string[] { "," }, StringSplitOptions.None)[1];


             using (MVCSystemContext db = new MVCSystemContext())
             {
                 M_UserProfile user = db.DB_UserProfiles.Single(e => e.UserId == userId);
                 Roles.AddUserToRole(user.UserName, roleName);
             }
             JsonResult result = new JsonResult();
             result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
             return result;
         }
         /// <summary>
         /// 删除角色
         /// </summary>
         /// <param name="id"></param>
         /// <returns></returns>
         public JsonResult RemoveRole(string id)
         {
             int userId = int.Parse(id.Split(new string[] { "," }, StringSplitOptions.None)[0]);
             string roleName = id.Split(new string[] { "," }, StringSplitOptions.None)[1];


             using (MVCSystemContext db = new MVCSystemContext())
             {
                 M_UserProfile user = db.DB_UserProfiles.Single(e => e.UserId == userId);
                 Roles.RemoveUserFromRole(user.UserName, roleName);
             }
             JsonResult result = new JsonResult();
             result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
             return result;
         }
         /// <summary>
         /// 释放已使用过且不再需要使用的组件
         /// </summary>
         /// <param name="disposing"></param>
         protected override void Dispose(bool disposing)
         {
             db.Dispose();
             base.Dispose(disposing);
         }
    }
}
View Code

RolesController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using MVCSystem.Web.Common;
using MVCSystem.Web.Filters;
using MVCSystem.Web.Models;

namespace MVCSystem.Web.Areas.Admin.Controllers
{
    [InitializeSimpleMembership]
    public class RolesController : BaseController
    {
        //
        // GET: /Admin/Roles/
        /// <summary>
        /// 数据列表
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult GetList(GridPager pager)
        {
            var aList = db.DB_Roles.ToList();
            aList = aList.OrderByDescending(a => a.RoleId).ToList();
            var json = new
          {
              results = aList.Count,
              rows = aList.Select(a => new
                      {
                          RoleID = a.RoleId,
                          RoleName = a.RoleName,
                          State = (a.State == 1) ? "启用" : "禁用",
                          perName = getPerName(a.RoleId),
                          CZ = "<a href='javascript:;' onclick='SetPermission(" + a.RoleId + ")' id='SetPermission'>权限设置</a><a href='javascript:;' onclick='RolesEdit(" + a.RoleId + ")' id='Edit'>编辑</a><a href='javascript:;' onclick='DeleteShow(" + a.RoleId + ")' id='Delete'>删除</a>"

                      }).Skip((pager.pageIndex) * pager.limit).Take(pager.limit).ToArray()
          };
            return Json(json, JsonRequestBehavior.AllowGet);

        }
        private string getPerName(int id)
        {

            var gg = (from a in db.DB_PermissionsInRoles
                      join b in db.DB_Permission
                      on a.PermissionId equals b.PermissionId
                      group new { a.RoleId, b.PermissionName, a.PermissionId } by new { a.RoleId, b.PermissionName, a.PermissionId } into dd
                      select new
                      {
                          RoleId = dd.Key.RoleId,
                          perName = dd.Key.PermissionName,
                      }).ToList();
            var perNameStr = String.Join("、", gg.Where(a => a.RoleId == id).Select(b => b.perName).ToArray());
            return perNameStr;
        }

        /// <summary>
        /// 删除数据操作
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult RolesDelete(int id)
        {
            if (id > 0)
            {
                var aList = db.DB_Roles.Find(id);
                db.DB_Roles.Remove(aList);
                db.SaveChanges();
                return Json(1, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(0, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 修改角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult RolesEdit(int id)
        {
            var rList = db.DB_Roles.Find(id);
            return View(rList);
        }
        [HttpPost]
        public ActionResult RolesEdit(int id, FormCollection collection)
        {
            var rList = db.DB_Roles.Find(id);
            if (TryUpdateModel(rList))
            {
                rList.State = (collection.Get("State") == "1") ? 1 : 0;
                db.SaveChanges();
                return Content("<script>alert('编辑成功!');parent.location.reload();</script>");

            }
            else
            {
                return View(rList);
            }
        }
        /// <summary>
        /// 添加角色
        /// </summary>
        /// <returns></returns>
        public ActionResult RolesAdd()
        {
            ViewBag.permissionList = GetPermissionSelectList();
            return View();
        }
        [HttpPost]
        public ActionResult RolesAdd(M_Roles role,FormCollection collection, string[] permissions)
        {
            if (ModelState.IsValid)
            {
                if (db.DB_Roles.SingleOrDefault(e => e.RoleName == role.RoleName) == null)
                {
                    role.State = (collection.Get("State") == "1") ? 1 : 0;
                    M_Roles currentRole = db.DB_Roles.Add(role);
                    db.SaveChanges();
                    if (permissions != null)
                    {
                        foreach (var permissionId in permissions)
                        {
                            M_PermissionsInRoles pir = new M_PermissionsInRoles();
                            pir.RoleId = currentRole.RoleId;
                            pir.PermissionId = int.Parse(permissionId);
                            db.DB_PermissionsInRoles.Add(pir);
                            db.SaveChanges();
                        }
                    }
                    return Content("<script>alert('添加成功!');parent.location.reload();</script>");
                }
                else
                {
                    ViewBag.permissionList = GetPermissionSelectList();
                    TempData["ErrorMessage"] = "角色名称已存在";
                }
            }

            return View(role);
        }
        /// <summary>
        /// 获取权限列表
        /// </summary>
        /// <returns></returns>
        private string GetPermissionSelectList()
        {
            var str = new StringBuilder();
            str.Append("<div class='checkboxlist'>");
            foreach (var role in db.DB_Permission)
            {
                str.Append("<span  style='padding-left:10px;'>" + role.PermissionName + "</span>");
                str.Append("<input type='checkbox' value='" + role.PermissionId + "' name='permissions'/>");

            }
            str.Append("</div>");

            return str.ToString();
        }
        /// <summary>
        /// 设置角色权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult RolesSetPermission(int id)
        {
            var permissionsInRoles = db.DB_PermissionsInRoles.Where(r => r.RoleId == id).ToList();
            var permission = db.DB_Permission.ToList();
            var str = new StringBuilder();
            str.Append("<div class='checkboxlist'>");
            foreach (var per in permission)
            {
                str.Append("<span style='padding-left:10px;'>" + per.PermissionName + "</span>");
                string strCK = "";
                foreach (var perR in permissionsInRoles)
                {
                    if (per.PermissionId == perR.PermissionId)
                    {
                        strCK = "checked='checked'";
                    }
                }
                str.Append("<input type='checkbox'" + strCK + " value='" + per.PermissionId + "' name='roles' />");

            }
            str.Append("</div>");
            ViewBag.permissionList = str;
            ViewBag.RoleId = id;
            var rList = db.DB_Roles.Find(id);
            return View(rList);

        }
        /// <summary>
        /// 更改角色权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult SetPermission(string id)
        {
            int roleId = int.Parse(id.Split(new string[] { "," }, StringSplitOptions.None)[0]);
            int permissionId = int.Parse(id.Split(new string[] { "," }, StringSplitOptions.None)[1]);

            using (MVCSystemContext db = new MVCSystemContext())
            {
                M_PermissionsInRoles pir = new M_PermissionsInRoles();
                pir.RoleId = roleId;
                pir.PermissionId = permissionId;
                db.DB_PermissionsInRoles.Add(pir);
                db.SaveChanges();
            }
            JsonResult result = new JsonResult();
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return result;
        }
        /// <summary>
        /// 移除角色权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult RemovePermission(string id)
        {
            int roleId = int.Parse(id.Split(new string[] { "," }, StringSplitOptions.None)[0]);
            int permissionId = int.Parse(id.Split(new string[] { "," }, StringSplitOptions.None)[1]);

            using (MVCSystemContext db = new MVCSystemContext())
            {
                M_PermissionsInRoles pir = db.DB_PermissionsInRoles.Single(e => e.PermissionId == permissionId && e.RoleId == roleId);
                db.DB_PermissionsInRoles.Remove(pir);
                db.SaveChanges();
            }
            JsonResult result = new JsonResult();
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return result;
        }
    }
}
View Code

视图Users文件下的页面

Index.cshtml

@using MVCSystem.Web;
@{
    ViewBag.Title = "Index";
    Layout = "~/Areas/Admin/Views/Shared/_Layout_Admin.cshtml";
}
<form class="form-inline definewidth m20" action="index.html" method="get">    
    用户名称:
    <input type="text" name="username" id="username"class="abc input-default" placeholder="" value="">&nbsp;&nbsp;  
    <button type="submit" class="btn btn-primary">查询</button>&nbsp;&nbsp; <a href="/Admin/Users/UserProfilesAdd/" class="btn btn-success" id="addnew">新增用户</a>
</form>
<div id="gridList"  style=" width:96%;margin:10px auto;">     
</div>
<div id="windDlog" class="hidden">

</div>

    <script type="text/javascript">
        BUI.use(['bui/grid', 'bui/data'], function (Grid, Data) {
            var Grid = Grid,
          Store = Data.Store,
          columns = [
            { title: '用户名', dataIndex: 'UserName', width: 200 },
            { title: '邮箱', dataIndex: 'UserEmail', width: 200 },
            { title: '真实姓名', dataIndex: 'RealName', width: 200 },
            { title: '状态', dataIndex: 'State', width: 100 },
            { title: '用户角色', dataIndex: 'UserRole', width: 200 },
            { title: '操作', dataIndex: 'CZ', width: 200 }
          ];

            var store = new Store({
                url: '/Admin/Users/GetList',
                autoLoad: true, //自动加载数据
                pageSize: 3    // 配置分页数目
            }),
              grid = new Grid.Grid({
                  render: '#gridList',
                  columns: columns,
                  loadMask: true, //加载数据时显示屏蔽层
                  store: store,
                  // 底部工具栏
                  bbar: {
                      // pagingBar:表明包含分页栏
                      pagingBar: true
                  }
              });

            grid.render();
        });

        function DeleteShow(UserId) {
            BUI.use('bui/overlay',function(overlay){
                BUI.Message.Show({
               
                    msg : '你确定要删除吗?',
                    icon : 'question',
                    buttons : [
                      {
                          text:'确定',
                          elCls : 'button button-primary',
                          handler : function(){
                              $.post("/Admin/Users/UserProfilesDelete/" + UserId + "", function (data) {
                                 location.reload();
                                  if (data == 1) {
                                      BUI.Message.Show({
                                          msg: '删除成功',
                                          icon: 'success',
                                          buttons: [],
                                          autoHide: true,
                                          autoHideDelay: 1000
                                      });
                                  
                                  }
                                  else {
                                      BUI.Message.Show({
                                          msg: '删除失败',
                                          icon: 'error',
                                          buttons: [],
                                          autoHide: true,
                                          autoHideDelay: 1000
                                      });
                                  }

                                  
                              }, "json");
                          }
                      },
                      {
                          text:'取消',
                          elCls : 'button',
                          handler : function(){
                              this.close();
                          }
                      }
 
                    ]
          
                })
            })
        }


        function SetRole(userId){
            $("#windDlog").html("<iframe width='100%' height='98%' frameborder='0'' src='/Admin/Users/UserProfilesSetRole/" + userId + "'></iframe>");
            BUI.use(['bui/overlay','bui/form'],function(Overlay,Form){
                var dialog = new Overlay.Dialog({
                    title: '角色设置',
                    width: 250,
                    height: 200,
                    //配置DOM容器的编号
                    contentId: 'windDlog',
                    mask: false,
                    buttons: [
                      {
                          text: '确定',
                          elCls: 'button button-primary',
                          handler: function () {
                              location.reload();
                              this.close();
                          }
                      }
                    ],
                });
                dialog.show();
            })
        }
    </script>
View Code

UserProfilesAdd.cshtml

@model MVCSystem.Web.Areas.Admin.Models.AM_UserProfileViewModel

@{
    ViewBag.Title = "UserProfilesAdd";
    Layout = "~/Areas/Admin/Views/Shared/_Layout_Admin.cshtml";
}

<h2>@ViewBag.MrrTip</h2>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
        <table class="table table-bordered table-hover definewidth m10">
        <tr>
            <td width="10%" class="tableleft">登录名</td>
            <td> @Html.EditorFor(model => model.UserName)
            @Html.ValidationMessageFor(model => model.UserName)</td>
        </tr>
        <tr>
            <td width="10%" class="tableleft">密码</td>
            <td> @Html.EditorFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)</td>
        </tr>
        <tr>
            <td class="tableleft">真实姓名</td>
            <td>  @Html.EditorFor(model => model.RealName)
            @Html.ValidationMessageFor(model => model.RealName)</td>
        </tr>
        <tr>
            <td class="tableleft">邮箱</td>
            <td>  @Html.EditorFor(model => model.Email)
            @Html.ValidationMessageFor(model => model.Email)</td>
        </tr>
          <tr>
            <td class="tableleft">状态</td>
            <td>
                
                <span><input type="radio" name="State" value="1" checked="checked"/> 启用</span>
                 <span><input type="radio" name="State" value="0" /> 禁用</span>
              
            </td>
        </tr>
        <tr>
            <td class="tableleft">角色</td>
            <td>
                @Html.Raw(ViewBag.roleList)
            </td>
        </tr>
        
        <tr>
            <td class="tableleft"></td>
            <td>
                <button type="submit" class="btn btn-primary">保存</button>
                 &nbsp;&nbsp;<a href="/admin/Users/" class="btn btn-success" name="backid" id="backid">返回列表</a>
            </td>
        </tr>
    </table>
   
}
View Code

UserProfilesEdit.cshtml

@model MVCSystem.Web.Models.M_UserProfile

@{
    ViewBag.Title = "UserProfilesEdit";
    Layout = "~/Areas/Admin/Views/Shared/_Layout_Admin.cshtml";
}


@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
     @Html.HiddenFor(model => model.UserId)
     <table class="table table-bordered table-hover definewidth m10">
        <tr>
            <td width="10%" class="tableleft">登录名</td>
            <td> @Html.EditorFor(model => model.UserName)
            @Html.ValidationMessageFor(model => model.UserName)</td>
        </tr>
       
        <tr>
            <td class="tableleft">真实姓名</td>
            <td>  @Html.EditorFor(model => model.RealName)
            @Html.ValidationMessageFor(model => model.RealName)</td>
        </tr>
        <tr>
            <td class="tableleft">邮箱</td>
            <td>  @Html.EditorFor(model => model.Email)
            @Html.ValidationMessageFor(model => model.Email)</td>
        </tr>
        <tr>
            <td class="tableleft">状态</td>
            <td>
                @if(Model.State==1){
                <span><input type="radio" name="State" value="1" checked="checked"/> 启用</span>
                 <span><input type="radio" name="State" value="0" /> 禁用</span>
                }
                else{
                  <span><input type="radio" name="State" value="1"/> 启用</span>
                 <span><input type="radio" name="State" value="0" checked="checked"/> 禁用</span>
                }
            </td>
        </tr>
        
        <tr>
            <td class="tableleft"></td>
            <td>
                <button type="submit" class="button button-primary">保存</button>
                 &nbsp;&nbsp;<a href="/admin/Users/" class="btn btn-success" name="backid" id="backid">返回列表</a>
            </td>
        </tr>
    </table>
   
}
View Code

UserProfilesSetRole.cshtml

@model MVCSystem.Web.Models.M_UserProfile
@{
    ViewBag.Title = "UserProfilesSetRole";
    Layout = "~/Areas/Admin/Views/Shared/_Layout_Admin.cshtml";
}

@using (Html.BeginForm())
{
    <input type="hidden" id="User_ID" value="@Model.UserId"/>
    <div class="row">
          <div class="control-group span5">
            <label class="control-label">角色设置:<span id="updateMessage"></span></label>
            <div class="controls">
               @Html.Raw(ViewBag.roleList) 
            </div>
          </div>
        </div>
}
<script type="text/javascript">
    $(function () { 
        $(".controls input").change(function () {
            var sUserId = $("#User_ID").val();
            var value = sUserId + "," + $(this).val();

            if ($(this).is(":checked")) {

                var url = "/Admin/Users/SetRole/" + value;
            }
            else {
                url = "/Admin/Users/RemoveRole/" + value;
            }

            var objUpdateMessage = $("#updateMessage");
            $.getJSON(url, function (data) {
                if (objUpdateMessage.length > 0) {
                    objUpdateMessage.fadeIn();
                    objUpdateMessage.css("color", "green");
                    objUpdateMessage.html("设置成功!");
                    objUpdateMessage.fadeOut("slow");
                }
            });

        });
       
    })
</script>
View Code

视图Roles文件下的页面

Index.cshtml

@using MVCSystem.Web;
@{
    ViewBag.Title = "Index";
    Layout = "~/Areas/Admin/Views/Shared/_Layout_Admin.cshtml";
}
<form class="form-inline definewidth m20" action="index.html" method="get">    
    角色名称:
    <input type="text" name="username" id="username"class="abc input-default" placeholder="" value="">&nbsp;&nbsp;  
    <button type="submit" class="btn btn-primary">查询</button>&nbsp;&nbsp; <button type="button" onclick="RolesAdd()" class="btn btn-success" id="addnew">新增角色</button>
</form>
<div id="gridList"  style=" width:96%;margin:10px auto;">     
</div>
<div id="windDlog" class="hidden">

</div>

    <script type="text/javascript">
        BUI.use(['bui/grid', 'bui/data'], function (Grid, Data) {
            var Grid = Grid,
          Store = Data.Store,
          columns = [
            { title: '角色名称', dataIndex: 'RoleName', width: 200 },
            { title: '权限', dataIndex: 'perName', width: 200 },
            { title: '状态', dataIndex: 'State', width: 100 },
            { title: '操作', dataIndex: 'CZ', width: 200 }
          ];

            var store = new Store({
                url: '/Admin/Roles/GetList',
                autoLoad: true, //自动加载数据
                pageSize: 3    // 配置分页数目
            }),
              grid = new Grid.Grid({
                  render: '#gridList',
                  columns: columns,
                  loadMask: true, //加载数据时显示屏蔽层
                  store: store,
                  // 底部工具栏
                  bbar: {
                      // pagingBar:表明包含分页栏
                      pagingBar: true
                  }
              });

            grid.render();
        });

        function DeleteShow(UserId) {
            BUI.use('bui/overlay',function(overlay){
                BUI.Message.Show({
               
                    msg : '你确定要删除吗?',
                    icon : 'question',
                    buttons : [
                      {
                          text:'确定',
                          elCls : 'button button-primary',
                          handler : function(){
                              $.post("/Admin/Roles/RolesDelete/" + UserId + "", function (data) {
                                 location.reload();
                                  if (data == 1) {
                                      BUI.Message.Show({
                                          msg: '删除成功',
                                          icon: 'success',
                                          buttons: [],
                                          autoHide: true,
                                          autoHideDelay: 1000
                                      });
                                  
                                  }
                                  else {
                                      BUI.Message.Show({
                                          msg: '删除失败',
                                          icon: 'error',
                                          buttons: [],
                                          autoHide: true,
                                          autoHideDelay: 1000
                                      });
                                  }

                                  
                              }, "json");
                          }
                      },
                      {
                          text:'取消',
                          elCls : 'button',
                          handler : function(){
                              this.close();
                          }
                      }
 
                    ]
          
                })
            })
        }
        function RolesEdit(rolesId) {
            $("#windDlog").html("<iframe width='100%' height='98%' frameborder='0'' src='/Admin/Roles/RolesEdit/" + rolesId + "'></iframe>");
            BUI.use(['bui/overlay', 'bui/form'], function (Overlay, Form) {
                var dialog = new Overlay.Dialog({
                    title: '编辑角色',
                    width: 300,
                    height: 200,
                    //配置DOM容器的编号
                    contentId: 'windDlog',
                    mask: false,
                    buttons: [],
                });
                dialog.show();
            })
        }

        function RolesAdd() {

            $("#windDlog").html("<iframe width='100%' height='98%' frameborder='0'' src='/Admin/Roles/RolesAdd/'></iframe>");
            BUI.use(['bui/overlay', 'bui/form'], function (Overlay, Form) {
                var dialog = new Overlay.Dialog({
                    title: '添加角色',
                    width: 500,
                    height: 250,
                    //配置DOM容器的编号
                    contentId: 'windDlog',
                    mask: false,
                    buttons: [],
                });
                dialog.show();
            })
        }
        function SetPermission(rolesId) {
            $("#windDlog").html("<iframe width='100%' height='98%' frameborder='0'' src='/Admin/Roles/RolesSetPermission/" + rolesId + "'></iframe>");
            BUI.use(['bui/overlay','bui/form'],function(Overlay,Form){
                var dialog = new Overlay.Dialog({
                    title: '权限设置',
                    width: 500,
                    height: 200,
                    //配置DOM容器的编号
                    contentId: 'windDlog',
                    mask: false,
                    buttons: [
                      {
                          text: '确定',
                          elCls: 'button button-primary',
                          handler: function () {
                              location.reload();
                              this.close();
                          }
                      }
                    ],
                });
                dialog.show();
            })
        }
    </script>
View Code

RolesAdd.cshtml

@model MVCSystem.Web.Models.M_Roles

@{
    ViewBag.Title = "RolesEdit";
    Layout = "~/Areas/Admin/Views/Shared/_Layout_Admin.cshtml";
}

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
        <div class="row">
          <div class="control-group span6">
            <label class="control-label L">角色名称:</label>
            <div class="controls L">
               @Html.EditorFor(model => model.RoleName)
            @Html.ValidationMessageFor(model => model.RoleName)
            </div>
          </div>
         </div>
    <div class="row">
          <div class="control-group span6">
            <label class="control-label L">权限设置:</label>
            <div class="controls L">
               @Html.Raw(ViewBag.permissionList)
            </div>
          </div>
         </div>
        <div class="row">
            <div class="control-group span6">
                <label class="control-label L">状态:</label>
                <div class="controls L">
                        <span><input type="radio" name="State" value="1" checked="checked"/> 启用</span>
                        <span><input type="radio" name="State" value="0" /> 禁用</span>
                </div>
            </div>
        </div>
    <div><button type="submit" class="btn btn-primary">保存</button></div>
 } 
View Code

RolesEdit.cshtml

@model MVCSystem.Web.Models.M_Roles

@{
    ViewBag.Title = "RolesEdit";
    Layout = "~/Areas/Admin/Views/Shared/_Layout_Admin.cshtml";
}

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
        <div class="row">
          <div class="control-group span4">
            <label class="control-label L">角色名称:</label>
            <div class="controls L">
               @Html.EditorFor(model => model.RoleName)
            @Html.ValidationMessageFor(model => model.RoleName)
            </div>
          </div>
         </div>
        <div class="row">
            <div class="control-group span4">
                <label class="control-label L">状态:</label>
                <div class="controls L">
                    @if(Model.State==1){
                    <span><input type="radio" name="State" value="1" checked="checked"/> 启用</span>
                        <span><input type="radio" name="State" value="0" /> 禁用</span>
                    }
                    else{
                        <span><input type="radio" name="State" value="1"/> 启用</span>
                        <span><input type="radio" name="State" value="0" checked="checked"/> 禁用</span>
                    }
                </div>
            </div>
        </div>
    <div><button type="submit" class="btn btn-primary">保存</button></div>
 } 
View Code

RolesSetPermission.cshtml

@model MVCSystem.Web.Models.M_Roles
@{
    ViewBag.Title = "RolesSetPermission";
    Layout = "~/Areas/Admin/Views/Shared/_Layout_Admin.cshtml";
}

@using (Html.BeginForm())
{
    <input type="hidden" id="RoleId" value="@Model.RoleId"/>
    <div class="row">
          <div class="control-group span6">
            <label class="control-label">权限设置:<span id="updateMessage"></span></label>
            <div class="controls">
               @Html.Raw(ViewBag.permissionList) 
            </div>
          </div>
        </div>
}
<script type="text/javascript">
    $(function () { 
        $(".controls input").change(function () {
            var sUserId = $("#RoleId").val();
            var value = sUserId + "," + $(this).val();

            if ($(this).is(":checked")) {

                var url = "/Admin/Roles/SetPermission/" + value;
            }
            else {
                url = "/Admin/Roles/RemovePermission/" + value;
            }

            var objUpdateMessage = $("#updateMessage");
            $.getJSON(url, function (data) {
                if (objUpdateMessage.length > 0) {
                    objUpdateMessage.fadeIn();
                    objUpdateMessage.css("color", "green");
                    objUpdateMessage.html("设置成功!");
                    objUpdateMessage.fadeOut("slow");
                }
            });

        });
       
    })
</script>
View Code

 

最终运行效果如下

编辑用户:

新增用户:

用户角色:

编辑角色:

新增角色:

权限设置:

源码下载:http://www.yealuo.com/Sccnn/Detail?KeyValue=2f926407-f80b-4bff-a729-949a53efed7b

作者:boyzi007

出处:http://www.cnblogs.com/boyzi/

QQ:470797533

QQ交流群:364307742
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

posted @ 2016-01-18 10:26  落日知暮  阅读(874)  评论(0编辑  收藏  举报
作者:boyzi007 出处:http://www.cnblogs.com/boyzi/ QQ:470797533 QQ交流群:364307742 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。