Remove Assigned Users From Role In ASP.NET MVC

Before proceeding to this tutorial please go to,
In previous tutorial swe learned how to assign role to users,  here we will learn how to remove Role from assigned user. For this purpose we need to add a action method in account controller class. In previous tutorials we created a model class name is “AllroleWithAllUser” . we will use the same class here to pass this class in controller.

Following code is for “RemoveRoleForUser” in controller class.
  1. [HttpGet]  
  2. public ActionResult RemoveRoleAddedToUser()  
  3. {  
  4.     AssignRole objvm = new AssignRole();  
  5.     objvm.UserRolesList = GetAll_UserRoles();  
  6.     objvm.Userlist = GetAll_Users();  
  7.     return View(objvm);  
  8. }  
After creating action method for [HttpGet], now we need to add another action method for the [httpPost] . So the following is code for the “RemoveRoleForUser” action method for[httpPost] method.
  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public ActionResult RemoveRoleAddedToUser(AssignRole _assignRole)  
  4. {  
  5.     if (_assignRole.UserRoleName == "0")   
  6.     {  
  7.         ModelState.AddModelError("RoleName""select proper RoleName");  
  8.     }  
  9.     if (_assignRole.UserID == "0")   
  10.     {  
  11.         ModelState.AddModelError("UserName""select proper Username");  
  12.     }  
  13.     if (ModelState.IsValid)  
  14.     {  
  15.         int currentUserId = CheckUserWithUserRole(Convert.ToInt32(_assignRole.UserID));  
  16.         if (currentUserId == Convert.ToInt16(_assignRole.UserRoleName)) {  
  17.             var UserName = GetUserName_BY_UserID(Convert.ToInt32(_assignRole.UserID));  
  18.             var UserRoleName = GetRoleNameByRoleID(Convert.ToInt32(_assignRole.UserRoleName));  
  19.             Roles.RemoveUserFromRole(UserName, UserRoleName);  
  20.             ViewBag.ResultMessage = "User Role is removed successfully !";  
  21.         } else {  
  22.             ViewBag.ResultMessage = "This current user doesn't belong to selected user role.";  
  23.         }  
  24.         _assignRole.UserRolesList = GetAll_UserRoles();  
  25.         _assignRole.Userlist = GetAll_Users();  
  26.     } else {  
  27.         _assignRole.UserRolesList = GetAll_UserRoles();  
  28.         _assignRole.Userlist = GetAll_Users();  
  29.     }  
  30.     return View(_assignRole);  
  31. }  
Following is the code for removing the role for the respective user. 
Following is the code for checking that selected user belongs to the respective RolId.
  1. public int CheckUserWithUserRole(int UserId)   
  2. {  
  3.     using(UsersRoleContext context = new UsersRoleContext())  
  4.     {  
  5.         int RoleId = context.webpages_UsersInRole.Where(c => c.UserId == UserId).Select(c => c.RoleId).SingleOrDefault();  
  6.         return RoleId;  
  7.     }  
  8. }  
Now right click on the”
RemoveRoleAddedToUser” controller and add the view to this controller, this view contains the scaffold template as “Create” model class and model class as “assignRole”.

Create

After clicking add write the following code to this view,
  1. @model MvcMembershipProvider.Models.AssignRole  
  2. @ {  
  3.     ViewBag.Title = "RemoveRoleAddedToUser";  
  4. <  
  5. h2 > RemoveRoleAddedToUser < /h2> <  
  6.     link href = "~/bootstrap/css/bootstrap.min.css"  
  7. rel = "stylesheet" / >  
  8.     <  
  9.     script src = "~/bootstrap/js/bootstrap.min.js" > < /script>  
  10. @using(Html.BeginForm())   
  11. {  
  12.         @Html.AntiForgeryToken()  
  13.         @Html.ValidationSummary(true) <  
  14.             fieldset >  
  15.             <  
  16.             legend > AssignRole < /legend> <  
  17.             div class = "editor-label" >  
  18.             @Html.LabelFor(model => model.UserRoleName) <  
  19.             /div> <  
  20.             div class = "editor-field" >  
  21.             @ * @Html.EditorFor(model => model.UserRoleName) * @  
  22.         @Html.DropDownListFor(m => m.UserRoleName, newSelectList(Model.UserRolesList, "Value", "Text"),  
  23.             new {  
  24.                 style = "width:200px", @class = "form-control"  
  25.             })  
  26.         @Html.ValidationMessageFor(model => model.UserRoleName) <  
  27.             /div> <  
  28.             div class = "editor-label" >  
  29.             @Html.LabelFor(model => model.UserID) <  
  30.             /div> <  
  31.             div class = "editor-field" >  
  32.             @ * @Html.EditorFor(model => model.UserID) * @  
  33.         @Html.DropDownListFor(m => m.UserID, new SelectList(Model.Userlist, "Value", "Text"),  
  34.             new {  
  35.                 style = "width:200px", @class = "form-control"  
  36.             })  
  37.         @Html.ValidationMessageFor(model => model.UserID) <  
  38.             /div> <  
  39.             p >  
  40.             <  
  41.             input type = "submit"  
  42.         value = "Remove User Role" / >  
  43.             <  
  44.             /p> <  
  45.             /fieldset>  
  46.     } <  
  47.     div >  
  48.     @Html.ActionLink("Back to List", "Index") <  
  49.     /div>  
  50. @section Scripts {  
  51.     @Scripts.Render("~/bundles/jqueryval")  
  52. }  
Now run your application and go to the following URL,

http://localhost:50526/Account/RemoveRoleAddedToUser

Now select user and role type from dropdown list and then check this work.

select

Authorize attribute in controller

We can authorize or we can give permission to the controller using attribute. There is a attribute [Authorize] to authorize. Following is the code for giving the permission code to the controller. If you want to give permission to the “admin” to full controller , if user has the permission for admin then it will redirect to this page otherwise it will redirect to login page.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. namespace MvcMembershipProvider.Controllers  
  7. {  
  8.     [Authorize(Roles = "Admin")]  
  9.     public class Authonticate1Controller: Controller   
  10.     {  
  11.         public ActionResult Index()  
  12.         {  
  13.             return View();  
  14.         }  
  15.     }  
  16. }  
If you want to give permission to particular user then use the following code. Here only admin can access then action method.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. namespace MvcMembershipProvider.Controllers   
  7. {  
  8.     public class Authonticate1Controller: Controller   
  9.     {  
  10.         [Authorize(Roles = "Admin")]  
  11.         public ActionResult Index()  
  12.         {  
  13.             return View();  
  14.         }  
  15.     }  
  16. }  
And the following code for the particular action method for the particular user.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. namespace MvcMembershipProvider.Controllers   
  7. {  
  8.     public class Authonticate1Controller: Controller   
  9.     {  
  10.         [Authorize(Roles = "Admin", Users = "munesh")]  
  11.         public ActionResult Index()  
  12.         {  
  13.             return View();  
  14.         }  
  15.     }  
  16. }