Assigning Role To User In ASP.NET MVC Membership

Before proceeding to this article please go to Assigning Role to User in ASP.NET MVC Membership.

Here we will learn how to assign roles to the users in ASP.NET membership provider. For assigning the roles to the user we need to add a model for member list and roles List.

First add a model class in account model.cs class name is “AssignRolesToUsers”.

  1. public class AssignRole  
  2. {  
  3.     [Required(ErrorMessage = " Select proper UserRole Name")]  
  4.     public string UserRoleName  
  5.     {  
  6.         get;  
  7.         set;  
  8.     }  
  9.     [Required(ErrorMessage = "Select UserName")]  
  10.     public string UserID  
  11.     {  
  12.         get;  
  13.         set;  
  14.     }  
  15.     public List < SelectListItem > Userlist  
  16.     {  
  17.         get;  
  18.         set;  
  19.     }  
  20.     public List < SelectListItem > UserRolesList  
  21.     {  
  22.         get;  
  23.         set;  
  24.     }  
  25. }  
After creating the model we need to add a action method in controller class name is “AssignRolesToUsers”.
  1. [HttpGet]  
  2. public ActionResult AssignRolesToUsers()  
  3. {  
  4. }  
Now add a DbSet to the UserProfile class
  1. public class UsersRoleContext: DbContext  
  2. {  
  3.     public UsersRoleContext(): base("DBConnectionForMembership")  
  4.     {}  
  5.     public DbSet < Role > UserRoles  
  6.     {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public DbSet < UserProfile > UserProfile  
  11.     {  
  12.         get;  
  13.         set;  
  14.     }  
  15. }  
Now create two nonAction methods, getAllUsers and GetAllUserRoles in Account Controller.

So for that write the following code:
  1. [NonAction]  
  2. public List < SelectListItem > GetAll_UserRoles()  
  3. {  
  4.     List < SelectListItem > listrole = new List < SelectListItem > ();  
  5.     listrole.Add(new SelectListItem  
  6.     {  
  7.         Text = "select", Value = "0"  
  8.     });  
  9.     using(UsersRoleContext db = new UsersRoleContext())  
  10.     {  
  11.         foreach(var item in db.UserRoles)  
  12.         {  
  13.             listrole.Add(new SelectListItem  
  14.             {  
  15.                 Text = item.RoleName, Value = Convert.ToString(item.RoleId)  
  16.             });  
  17.         }  
  18.     }  
  19.     return listrole;  
  20. }  
  1. [NonAction]  
  2. public List < SelectListItem > GetAll_Users()  
  3. {  
  4.     List < SelectListItem > listuser = new List < SelectListItem > ();  
  5.     listuser.Add(new SelectListItem  
  6.     {  
  7.         Text = "Select", Value = "0"  
  8.     });  
  9.     using(UsersRoleContext db = new UsersRoleContext())  
  10.     {  
  11.         foreach(var item in db.UserProfile)  
  12.         {  
  13.             listuser.Add(new SelectListItem  
  14.             {  
  15.                 Text = item.UserName, Value = Convert.ToString(item.UserId)  
  16.             });  
  17.         }  
  18.     }  
  19.     return listuser;  
  20. }  
Now add the following code to the “AssignRolesToUsers” action method.
  1. [HttpGet]  
  2. public ActionResult AssignRolesToUsers()  
  3. {  
  4.     AssignRole _addignroles = new AssignRole();  
  5.     _addignroles.UserRolesList = GetAll_UserRoles();  
  6.     _addignroles.Userlist = GetAll_Users();  
  7.     return View(_addignroles);  
  8. }  
Now after assigning the object valuewe need to add view for this action method so for that right click on this action method and select strongly typed model as “AssignRoles” and scaffold template as create.



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

http://localhost:50526/Account/AssignRolesToUsers



Add role to the user

Now here we will create action method to add the role to the users with the post method.

Write the following code in Post action method for the “AssignRolesToUsers”.
  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public ActionResult AssignRolesToUsers(AssignRole _assignRole)  
  4. {  
  5.     if (_assignRole.UserRoleName == "0")  
  6.     {  
  7.         ModelState.AddModelError("RoleName"" select UserRoleName");  
  8.     }  
  9.     if (_assignRole.UserID == "0")  
  10.     {  
  11.         ModelState.AddModelError("UserName"" select Username");  
  12.     }  
  13.     if (ModelState.IsValid)  
  14.     {  
  15.         if (Get_CheckUserRoles(Convert.ToInt32(_assignRole.UserID)) == true)  
  16.         {  
  17.             ViewBag.ResultMessage = "Current user is already has the role";  
  18.         }  
  19.         else  
  20.         {  
  21.             var UserName = GetUserName_BY_UserID(Convert.ToInt32(_assignRole.UserID));  
  22.             var UserRoleName = GetRoleNameByRoleID(Convert.ToInt32(_assignRole.UserRoleName));  
  23.             Roles.AddUserToRole(UserName, UserRoleName);  
  24.             ViewBag.ResultMessage = "Username added to role successfully !";  
  25.         }  
  26.         _assignRole.UserRolesList = GetAll_UserRoles();  
  27.         _assignRole.Userlist = GetAll_Users();  
  28.         return View(_assignRole);  
  29.     }  
  30.     else  
  31.     {  
  32.         _assignRole.UserRolesList = GetAll_UserRoles();  
  33.         _assignRole.Userlist = GetAll_Users();  
  34.     }  
  35.     return View(_assignRole);  
  36. }  
Following code for get UserName by using userid
  1. public string GetUserName_BY_UserID(int UserId)  
  2. {  
  3.     using(UsersRoleContext context = new UsersRoleContext())  
  4.     {  
  5.         var UserName = (from UP in context.UserProfile where UP.UserId == UserId select UP.UserName).SingleOrDefault();  
  6.         return UserName;  
  7.     }  
  8. }  
Following code for get UserRoleName by using userRoleId.
  1. public string GetRoleNameByRoleID(int RoleId)  
  2. {  
  3.     using(UsersRoleContext context = new UsersRoleContext())  
  4.     {  
  5.         var roleName = (from UP in context.UserRoles where UP.RoleId == RoleId select UP.RoleName).SingleOrDefault();  
  6.         return roleName;  
  7.     }  
  8. }  
Following code is for checking if current user has role name or not.
  1. public bool Get_CheckUserRoles(int UserId)  
  2. {  
  3.     using(UsersRoleContext context = new UsersRoleContext())  
  4.     {  
  5.         var data = (from WR in context.webpages_UsersInRole join R in context.UserRoles on WR.RoleId equals R.RoleId where WR.UserId == UserId orderby R.RoleId select new  
  6.         {  
  7.             WR.UserId  
  8.         }).Count();  
  9.         if (data > 0)  
  10.         {  
  11.             return true;  
  12.         }  
  13.         else  
  14.         {  
  15.             return false;  
  16.         }  
  17.     }  
  18. }  
Now run your application and go to the following URL and check the entries

http://localhost:50526/Account/AssignRolesToUsers



Database table is:



Create a view with all roles and all the users.

First for this add a model in account.cs class under model folder. So code for this is:
  1. public class AllroleWithAllUser  
  2. {  
  3.    public string UserRoleName { getset; }  
  4.    public string UserName { getset; }  
  5.    public IEnumerable<AllroleWithAllUser> AllDetailsUserlist { getset; }  
  6. }  
Write a nonAction method in controller to get all user with respective UserRole.
  1. [NonAction]  
  2. public List < AllroleWithAllUser > GetUserNameResepectiveToRole()  
  3. {  
  4.     using(UsersRoleContext db = new UsersRoleContext())  
  5.     {  
  6.         var Alldata = (from User in db.UserProfile join WU in db.webpages_UsersInRole on User.UserId equalsWU.UserId join WR in db.UserRoles on WU.RoleId equals WR.RoleId select new AllroleWithAllUser  
  7.         {  
  8.             UserName = User.UserName, UserRoleName = WR.RoleName  
  9.         }).ToList();  
  10.         return Alldata;  
  11.     }  
  12. }  
Now write a action method for getting this:
  1. [HttpGet]  
  2. public ActionResult DisplayAllUserroles()  
  3. {  
  4.    AllroleWithAllUser _alluserWithRole = new AllroleWithAllUser();  
  5.    _alluserWithRole.AllDetailsUserlist = GetUserNameResepectiveToRole();  
  6.    return View(_alluserWithRole);  
  7. }  
Now we need to add a view for showing All user with their respective Role. So right click on action method and add a view with scaffold template as empty.



And the write following code in the view:
  1. @model MvcMembershipProvider.Models.AllroleWithAllUser  
  2. @using GridMvc.Html  
  3. @{  
  4.    ViewBag.Title = "DisplayAllUserroles";  
  5. }  
  6. <h2>DisplayAllUserroles</h2>  
  7. <link href="~/Content/Gridmvc.css" rel="stylesheet" />  
  8. <link href="~/bootstrap/css/bootstrap.min.css" rel="stylesheet" />  
  9. <script src="~/Scripts/jquery-1.9.1.min.js"></script>  
  10. <script src="~/Scripts/gridmvc.js"></script>  
  11. @Html.Grid(Model.AllDetailsUserlist).Columns(columns =>  
  12. {  
  13.    columns.Add(c => c.UserName).Titled("UserName").Filterable(true).SetWidth(300);  
  14.    columns.Add(c => c.UserRoleName).Titled("RoleName").Filterable(true).SetWidth(300);  
  15. }).WithPaging(10).Sortable(true)  
Now run your application and go to following URL

http://localhost:50526/Account/DisplayRoleForUsers

 


Similar Articles