asp.net Identity2 角色(Role)的使用,二角色管理,角色控制器和视图

新建一个AdminViewModel 文件,建立视图模型类

public class RoleViewModel

{

public string Id { get; set; }

[Required(AllowEmptyStrings=false)]

[Display(Name="角色名称")]

public string Name { get; set; }

[Display(Name="角色描述")]

[StringLength(50,ErrorMessage="{0}不能超过50个字符")]

[DataType(DataType.MultilineText)]

public string Description { get; set; }

}

新建一个角色控制器RoleAdminController,并初始化UserManager值。

public class RoleAdminController : Controller

{

public RoleAdminController()

{ }

//构造函数注入;

public RoleAdminController(ApplicationUserManager userManager, ApplicationRoleManager roleManager)

{

UserManager = userManager;

RoleManager = roleManager;

}

//定义字段

private ApplicationUserManager _userManager;

public ApplicationUserManager UserManager

{

get

{

return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();//Microsoft.AspNet.Identity.Owin 命名空间下。 空值合并运算符。

}

set

{

_userManager = value;

}

}

private ApplicationRoleManager _roleManager;

public ApplicationRoleManager RoleManager

{

get

{

return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();

}

set

{

_roleManager = value;

}

}

角色列表 要想在角色首页中列表每个角色的用户

模型:

public class IndexRoleViewModel

{

public string Id { get; set; }

[Required(AllowEmptyStrings = false)]

[Display(Name = "角色名称")]

public string Name { get; set; }

[Display(Name = "角色描述")]

[StringLength(50, ErrorMessage = "{0}不能超过50个字符")]

[DataType(DataType.MultilineText)]

public string Description { get; set; }

public List<ApplicationUser> ApplicationUsers { get; set; }

}

}

控制器

// GET: Admin/RoleAdmin

public async Task<ActionResult> Index()

{

var rolesList =new List<IndexRoleViewModel>();

foreach (var role in await RoleManager.Roles.ToListAsync())

{

var _IndexRoleViewModel = new IndexRoleViewModel()

{

Id = role.Id,

Name = role.Name,

Description = role.Description,

ApplicationUsers =new List<ApplicationUser>() //特别注意,初始化一个空的List泛型集合。如果不初始化,将为触发一个引用为Null的异常。

};

foreach (var user in await UserManager.Users.ToListAsync())

{

if (UserManager.IsInRole(user.Id,role.Name)) //遍历用户,如果该用户有此角色,就将此用户加入到集合中。

{

_IndexRoleViewModel.ApplicationUsers.Add(user);

}

}

rolesList.Add(_IndexRoleViewModel); //最后将此ViewModel 加入到列表中,返回给视图。

}

return View(rolesList.ToList()); //异步方法在 System.Data.Entity命名空间下面。

}

视图:

@model IEnumerable<MajorConstruction.Areas.Admin.Models.IndexRoleViewModel>

@{

ViewBag.Title = "角色列表";

}

<h2>@ViewBag.Title</h2>

<hr />

<table class="table table-striped table-hover">

<thead>

<tr>

<th>

@Html.DisplayName("角色名称")

</th>

<th>

@Html.DisplayNameFor(model => model.Description)

</th>

<th>@Html.DisplayName("拥有此角色的成员")</th>

<th></th>

</tr>

</thead>

<tbody>

@foreach (var item in Model)

{

<tr>

<td>

@Html.DisplayFor(modelItem => item.Name)

</td>

<td>

@Html.DisplayFor(modelItem => item.Description)

</td>

<td>

<ol>

@foreach (var userForRole in item.ApplicationUsers)

{

<li>@userForRole.UserName | @userForRole.RealName</li>

}

</ol>

</td>

<td>

@Html.ActionLink("编辑", "Edit", new { id = item.Id }) |

@Html.ActionLink("详细", "Details", new { id = item.Id })

</td>

</tr>

}

</tbody>

</table>

角色详细信息

控制器:

// GET: Admin/RoleAdmin/Details/5

public async Task<ActionResult> Details(string id)

{

if (id == null)

{

return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

}

var role = await RoleManager.FindByIdAsync(id);

if (role == null)

{

return HttpNotFound();

}

var users = new List<ApplicationUser>(); //首先要定义一个List泛型容器,用来存放User。

foreach (var user in UserManager.Users.ToList())

{

if(await UserManager.IsInRoleAsync(user.Id,role.Name))

{

users.Add(user);

}

}

ViewBag.Users = users; //如果只是一个集合,可以不使用ViewModel ,而是使用ViewBag动态对象,将数据带入View中。

ViewBag.UserCount = users.Count();

return View(role);

}

视图:

@model MajorConstruction.Areas.Admin.Models.ApplicationRole

@{

ViewBag.Title = "角色详细信息";

}

<h2>@ViewBag.Title</h2>

<hr />

<div>

<dl class="dl-horizontal">

<dt>

角色名称

</dt>

<dd>

@Html.DisplayFor(model => model.Name)

</dd>

<dt>

@Html.DisplayNameFor(model => model.Description)

</dt>

<dd>

@Html.DisplayFor(model => model.Description)

</dd>

</dl>

</div>

<h4>拥有此角色的所有成员</h4>

@if (ViewBag.UserCount == 0)

{

<hr />

<p>没有用户拥有此角色</p>

}

<table class="table table-striped table-hover">

<tr>

<th>用户名</th>

<th>姓名</th>

<th>性别</th>

<th>邮箱</th>

</tr>

@foreach (var item in ViewBag.Users )

{

<tr>

<td>@item.UserName</td>

<td>@item.RealName</td>

<td>@item.Gender</td>

<td>@item.Email</td>

</tr>

}

</table>

<p>

@Html.ActionLink("编辑", "Edit", new { id = Model.Id }) |

@Html.ActionLink("返回角色列表", "Index")

</p>

编辑角色: 可以使用T4模板快速生成,没有特别的地方。

控制器:

public async Task<ActionResult> Edit(string id)

{

if (id == null)

{

return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

}

var role = await RoleManager.FindByIdAsync(id);

if (role == null)

{

return HttpNotFound();

}

RoleViewModel roleViewModel = new RoleViewModel { Id = role.Id, Name = role.Name, Description = role.Description };

return View(roleViewModel);

}

[HttpPost]

[ValidateAntiForgeryToken]

public async Task<ActionResult> Edit([Bind(Include = "Id,Name,Description")] RoleViewModel roleModel)

{

if (ModelState.IsValid)

{

var role = await RoleManager.FindByIdAsync(roleModel.Id);

role.Name = roleModel.Name;

role.Description = roleModel.Description;

await RoleManager.UpdateAsync(role);

return RedirectToAction("Index");

}

return View(roleModel);

}

视图:

@model MajorConstruction.Areas.Admin.Models.RoleViewModel

@{

ViewBag.Title = "编辑角色";

}

<h2>@ViewBag.Title</h2>

<hr />

@using (Html.BeginForm())

{

@Html.AntiForgeryToken()

<div class="form-horizontal">

@Html.ValidationSummary(true, "", new { @class = "text-danger" })

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

@Html.HiddenFor(model =>model.Name)

<div class="form-group">

@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

<div class="col-md-10">

<p class="form-control-static">@Html.DisplayFor(model =>model.Name)</p>

</div>

</div>

<div class="form-group">

@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })

<div class="col-md-10">

@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control",rows="5" } })

@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger", })

</div>

</div>

<div class="form-group">

<div class="col-md-offset-2 col-md-10">

<input type="submit" value="保存" class="btn btn-default" />

</div>

</div>

</div>

}

<div>

@Html.ActionLink("返回角色列表", "Index")

</div>

@section Scripts {

@Scripts.Render("~/bundles/jqueryval")

}

删除角色和新建角色 和Vs 自动生成的没有两样,在一般的后台控制管理系统中,权限角色的授权都是写死在程序中,所以没有必要提供新建角色和删除角色的功能,只需要在角色初始化器中初始化就可以了。

但是,如果是在动态分配角色权限,比如某个角色对某个操作有查看的权限,就需要有增和删的功能了。