مدیریت Role در MVC 5
دوشنبه 22 شهریور 1395این مقاله ، دوره ای برای آموزش ایجاد یک مدیریت ساده Role برای ASP.Net MVC 5 است . این ساده است ، چون همه چیزی که ما نیاز داریم در یک View قرار دارد .
قبل از مطالعه این مقاله ، بهتر است با Role ها آشنا شوید . برای آشنایی و مطالعه در مورد Role ها اینجا کلیک کنید .
معرفی :
نقش این مقاله ، آموزش تولید یک داشبورد ساده برای مدیریت نقش ها و کاربران در نقش خودشان است . که فقط یک Controller و دو View میخواهد . برا ی فرمت دهی از Bootstrap استفاده کرده ایم . زمانی که کار ما تمام شد ، خروجی ای همانند زیر خواهیم داشت :

پیشنیاز ها :
حال یک پروژه جدید ASP.Net Web Application با استفاده از MVC ایجاد میکنیم . در این مقاله ما برای احراز هویت از نوع "Individual User Accounts" استفاده کرده ایم .
دانش اطلاعات پایه و اساسی در مورد برنامه نویسی و کار با MVC برای مطالعه این مقاله الزامیست .
وظایف :
اساسا ، شما باید در مرحله اول یک Controller و دو View ایجاد کنید . Index View ، تقریبا 99 درصد از چیزی که ما میخواهیم را انجام میدهد . View دیگر تنها وظیفه اش تغییر نام نقشها در صورت نیاز است .
مرحله اول :
یک Controller با نام RolesController ایجاد کنید . برای این کار ، روی فولدر Controller راست کلیک کرده و Add را بزنید ، سپس "MVC 5 Controller Empty" را انتخاب کنید . در زیر کدهایی که در این Controller باید قرار گیرند را مشاهده میکنید ، قبل از اضافه کردن این کد ها به پروژه کد نگاهی به قسمت Using داشته باشید . به MyDatabase که bold هم شده است ، نام پایگاه داده خودتون را قرار دهید .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using MyDatabase.Models;
namespace MyDatabase.Controllers
{
public class RolesController : Controller
{
public ActionResult Index()
{
// Populate Dropdown Lists
var context = new Models.ApplicationDbContext();
var rolelist = context.Roles.OrderBy(r => r.Name).ToList().Select(rr =>
new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
ViewBag.Roles = rolelist;
var userlist = context.Users.OrderBy(u => u.UserName).ToList().Select(uu =>
new SelectListItem { Value = uu.UserName.ToString(), Text = uu.UserName }).ToList();
ViewBag.Users = userlist;
ViewBag.Message = "";
return View();
}
// GET: /Roles/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Roles/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
var context = new Models.ApplicationDbContext();
context.Roles.Add(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole()
{
Name = collection["RoleName"]
});
context.SaveChanges();
ViewBag.Message = "Role created successfully !";
return RedirectToAction("Index");
}
catch
{
return View();
}
}
public ActionResult Delete(string RoleName)
{
var context = new Models.ApplicationDbContext();
var thisRole = context.Roles.Where(r => r.Name.Equals(RoleName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
context.Roles.Remove(thisRole);
context.SaveChanges();
return RedirectToAction("Index");
}
//
// GET: /Roles/Edit/5
public ActionResult Edit(string roleName)
{
var context = new Models.ApplicationDbContext();
var thisRole = context.Roles.Where(r => r.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
return View(thisRole);
}
//
// POST: /Roles/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Microsoft.AspNet.Identity.EntityFramework.IdentityRole role)
{
try
{
var context = new Models.ApplicationDbContext();
context.Entry(role).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// Adding Roles to a user
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RoleAddToUser(string UserName, string RoleName)
{
var context = new Models.ApplicationDbContext();
if (context == null)
{
throw new ArgumentNullException("context", "Context must not be null.");
}
ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
userManager.AddToRole(user.Id, RoleName);
ViewBag.Message = "Role created successfully !";
// Repopulate Dropdown Lists
var rolelist = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
ViewBag.Roles = rolelist;
var userlist = context.Users.OrderBy(u => u.UserName).ToList().Select(uu =>
new SelectListItem { Value = uu.UserName.ToString(), Text = uu.UserName }).ToList();
ViewBag.Users = userlist;
return View("Index");
}
//Getting a List of Roles for a User
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult GetRoles(string UserName)
{
if (!string.IsNullOrWhiteSpace(UserName))
{
var context = new Models.ApplicationDbContext();
ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
ViewBag.RolesForThisUser = userManager.GetRoles(user.Id);
// Repopulate Dropdown Lists
var rolelist = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
ViewBag.Roles = rolelist;
var userlist = context.Users.OrderBy(u => u.UserName).ToList().Select(uu =>
new SelectListItem { Value = uu.UserName.ToString(), Text = uu.UserName }).ToList();
ViewBag.Users = userlist;
ViewBag.Message = "Roles retrieved successfully !";
}
return View("Index");
}
//Deleting a User from A Role
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteRoleForUser(string UserName, string RoleName)
{
var account = new AccountController();
var context = new Models.ApplicationDbContext();
ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
if (userManager.IsInRole(user.Id, RoleName))
{
userManager.RemoveFromRole(user.Id, RoleName);
ViewBag.Message = "Role removed from this user successfully !";
}
else
{
ViewBag.Message = "This user doesn't belong to selected role.";
}
// Repopulate Dropdown Lists
var rolelist = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
ViewBag.Roles = rolelist;
var userlist = context.Users.OrderBy(u => u.UserName).ToList().Select(uu =>
new SelectListItem { Value = uu.UserName.ToString(), Text = uu.UserName }).ToList();
ViewBag.Users = userlist;
return View("Index");
}
}
}
در قسمت Views یک فولدر با نام Roles ایجاد کنید . سپس دو View مورد نظر را با نام های Edit و Index به آن اضافه کنید .

مرحله سوم : کدهای زیر را در Index View قرار دهید :
@{
ViewBag.Title = "ManageUserRoles";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row col-sm-12 col-lg-12 col-md-12">
<h1>Role Manager</h1>
<br />
</div>
<div class="row col-sm-12 col-lg-12 col-md-12">
<div class="col-sm-6 col-lg-6 col-md-6">
<div class="panel panel-primary">
<div class="panel-heading">
<h4>Role List</h4>
</div>
<div class="panel-body">
<table class="table table-striped table-hover col-sm-6 col-lg-6 col-md-6 ">
@foreach (var role in ViewBag.Roles)
{
<tr>
<td class="col-sm-1 col-lg-5 col-md-5">
<strong>@role.Text </strong>
</td>
<td class="col-sm-1 col-lg-1 col-md-1">
<span onclick="return confirm('Are you sure to delete?')"><a href="/Roles/Delete?RoleName=@role.Text" class="delLink" style="color:red;">Delete</a></span> |
@Html.ActionLink("Edit", "Edit", new { roleName = @role.Text })
</td>
</tr>
}
</table>
</div> <!-- End Panel Body-->
</div> <!-- End Panel -->
<div class="panel panel-primary">
<div class="panel-heading">
<h4>Create A New Role</h4>
</div>
<div class="panel-body">
@using (Html.BeginForm("Create", "Roles", new { @class = "form-horizontal" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div>
Role name: @Html.TextBox("RoleName")
<input type="submit" value="Save" class="btn-primary" />
</div>
}
</div> <!--End Panel Body-->
</div> <!--End Panel-->
</div> <!--End First Column-->
<div class="col-sm-6 col-lg-6 col-md-6">
<div class="panel panel-primary">
<div class="panel-heading">
<h4>Add a Role to a User</h4>
</div>
<div class="panel-body">
@using (Html.BeginForm("RoleAddToUser", "Roles"))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<p>User Name: @Html.DropDownList("UserName", (IEnumerable<SelectListItem>)ViewBag.Users, "Select ...")</p>
<p>Role Name: @Html.DropDownList("RoleName", (IEnumerable<SelectListItem>)ViewBag.Roles, "Select ...")</p>
<p><input type="submit" value="Save" class="btn-primary" /></p>
}
</div> <!-- End Panel Body-->
</div> <!-- End Panel -->
<div class="panel panel-primary">
<div class="panel-heading">
<h4>List Roles for a User</h4>
</div>
<div class="panel-body">
@using (Html.BeginForm("GetRoles", "Roles"))
{
@Html.AntiForgeryToken()
<p>
User Name: @Html.DropDownList("UserName", (IEnumerable<SelectListItem>)ViewBag.Users, "Select ...")
<input type="submit" value="Get Roles for this User" class="btn-primary" />
</p>
}
@if (ViewBag.RolesForThisUser != null)
{
<div class="alert-info">
<strong>Roles for this user </strong>
<ol>
@foreach (string s in ViewBag.RolesForThisUser)
{
<li>@s</li>
}
</ol>
</div>
}
</div> <!-- End Panel Body-->
</div> <!-- End Panel -->
<div class="panel panel-primary">
<div class="panel-heading">
<h4>Remove Role from User</h4>
</div>
<div class="panel-body">
@using (Html.BeginForm("DeleteRoleForUser", "Roles"))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<p>User Name: @Html.DropDownList("UserName", (IEnumerable<SelectListItem>)ViewBag.Users, "Select ...")</p>
<p>Role Name: @Html.DropDownList("RoleName", (IEnumerable<SelectListItem>)ViewBag.Roles, "Select ...")</p>
<p><input type="submit" value="Delete this user from Role" class="btn-primary" /></p>
}
</div> <!-- End Panel Body-->
</div> <!-- End Panel -->
</div> <!--End Second Column-->
</div> <!--Overall Page Wrapper-->
<div class="alert-info col-sm-12 col-lg-12 col-md-12">
@ViewBag.Message
</div>
مرحله 4 : کدهای زیر را در Edit View قرار دهید :
@model Microsoft.AspNet.Identity.EntityFramework.IdentityRole
@{
ViewBag.Title = "Edit Roles";
}
<h2>Edit Role</h2>
@Html.ActionLink("Return to Role Manager", "Index")
<hr />
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.Id)
<div>
Role name
</div>
<p>
@Html.TextBoxFor(model => model.Name)
</p>
<input type="submit" value="Save" />
}
مرحله 5 : (اختیاری) یک Menu list به Layout.cshtml_ اضافه کنید .
<li>@Html.ActionLink("Role Manager", "Index", "Roles")</li>
نتیجه گیری :
شما بهتر است که یک داشبورد برای ایجاد ، ویرایش و حذف نقش ها و انتساب آنها به کاربران داشته باشید .
آموزش asp.net mvc
- ASP.net MVC
- 2k بازدید
- 12 تشکر