Display Roles For The Users In ASP.NET MVC Membership

Before proceeding to this tutorial please go to ASP.NET MVC Membership Provider.

In the previous tutorial we learned how to use membership provider in ASP.NET. Here we will learn how to Display Roles for the users in ASP.NET MVC Membership.

First proceeding to this we need to add a class or we need a model name which is Role. Add this role model inside the account model.

Add the following code to the account model.cs class.

  1. [Table("webpages_Roles")]  
  2. public class Role  
  3. {  
  4.     [Required(ErrorMessage = "Enter Role name")]  
  5.     [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]  
  6.     public string RoleName  
  7.     {  
  8.         get;  
  9.         set;  
  10.     }  
  11.     [Key]  
  12.     [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]  
  13.     public int RoleId  
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18. }  
After creating this Role model we need to add a Acton method named RoleCreate for HttpPost and HttpGet, so for that write the following code in account controller.

 

  1. [HttpGet]  
  2. public ActionResult UserRole()  
  3. {  
  4.     return View(new Role());  
  5. }  
  6. [HttpPost]  
  7. public ActionResult UserRole(Role role)  
  8. {  
  9.     return View(role);  
  10. }  
After creating action method for Role we need to add a view for this. For adding view right click on the “UserRole” action method a window will open there you select model class as Role model and select scaffold template as Create. And after selecting all these click on Add.



It will add a view for you and you will see this view under the account folder in View.



Now run your application and login to the page which you created account before. After logging in to account, navigate to the following URL

http://localhost:50526/Account/UserRole

When you will hit this URL it will go to user Role view and page will look like this



After making this view we need to insert role to database so for that we need to add code to insert data into database , so for that we need to add code in HttpPost method of UserRole action method.

Inside this action method there is a property whose name is [Roles.RoleExists(role.RoleName) ]to check that this Role already exists or not in database,  it returns Boolean value. So write the following code in UserRoleAction method.
  1. [HttpPost]  
  2. public ActionResult UserRole(Role role)  
  3. {  
  4.     if (ModelState.IsValid)  
  5.     {  
  6.         if (Roles.RoleExists(role.RoleName))  
  7.         {  
  8.             ModelState.AddModelError("Error"" This Rolename already exists");  
  9.             return View(role);  
  10.         }  
  11.         else  
  12.         {  
  13.             Roles.CreateRole(role.RoleName);  
  14.             return RedirectToAction("RoleIndex""Account");  
  15.         }  
  16.     }  
  17.     else  
  18.     {  
  19.         ModelState.AddModelError("Error""Please enter proper Username and Password");  
  20.     }  
  21.     return View(role);  
  22. }  
So far we created Role for the user. Now we will learn how to assign role to the user.

Assign Roles to the user And Display the Role

For displaying all the user roles we will use code first approach so for that we have to create a class name, “userContext” which will be inherited from the “DbContext” class. If you are in internet application then it already exists in account model at top. Code for this class is like following:

 

  1. public class UsersRoleContext: DbContext  
  2. {  
  3.     public UsersRoleContext(): base("DBConnectionForMembership")  
  4.     {}  
  5.     public DbSet < Role > UserRoles  
  6.     {  
  7.         get;  
  8.         set;  
  9.     }  
  10. }  
DBConnectionForMembership is the connection string name which we defined in web config file.

Now we need to add action method for displaying the role of users and add a action methos in account controller class name is “DisplayRoleForUsers”.
  1. [HttpGet]  
  2. public ActionResult DisplayRoleForUsers()  
  3. {  
  4.     IEnumerable < Role > ListRoles;  
  5.     using(UsersRoleContext db = new UsersRoleContext())  
  6.     {  
  7.         ListRoles = db.UserRoles.ToList();  
  8.     }  
  9.     return View(ListRoles);  
  10. }  
After adding action method, now need to add view for displaying the role of user so for that right click onDisplayRoleForUsers action method add a view without creating strongly typed view.



Now this view will create an empty view and for showing role of user we need a grid.

Adding MVC Grid to application

For adding grid to the application right click on the application and select “Nuget package manager”.



After clicking on nugget packet manager a window will open there you search “Grid.Mvc” under online panel. And install this grid to the application.

After adding grid to the application go the “DisplayRoleForUsers” view.

Add grid.mvc to this view



Write the following code to this view:

 

  1. @model IEnumerable<MvcMembershipProvider.Models.Role>  
  2. @using GridMvc.Html  
  3. @{  
  4.    ViewBag.Title = "Display roles for users";  
  5. }  
  6. <h2>DisplayAllRoles</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).Columns(columns =>  
  12. {  
  13.    columns.Add(c => c.RoleId).Titled("Role ID").SetWidth(300);  
  14.    columns.Add(c => c.RoleName).Titled("RoleName").Filterable(true).SetWidth(300);  
  15. }).WithPaging(5).Sortable(true)  
Now run your application and go to the followinf URL and see the output

http://localhost:50526/Account/DisplayRoleForUsers

 


Similar Articles