Introduction
This article will talk about role-based menus in ASP.NET MVC. I will discuss them with proper examples and demonstration. I strongly recommended you read my previous articles before continuing with this one. This article is in continuation of the previous article.
Step 1
Open Visual Studio 2015 or an editor of your choice and create a new project.
Step 2
Choose the "web application" project and give an appropriate name to your project.
Step 3
Select the "empty" template, check on the MVC box and click OK.
Step 4
Right-click on the Models folder and add a database model. Add Entity Framework now. For that, right-click on Models folder, select Add, then select New Item.
You will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name EmployeeModel (this name is not mandatory, you can give any name) and click "Add."
After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click "Next".
After clicking on "Next", a window will appear. Choose New Connection. Another window will appear. Add your server name - if it is local, then enter a dot (.). Choose your database and click "OK".
The connection will be added. If you wish, save the connection name as you want. You can change the name of your connection below. It will save the connection in the web config. Now, click "Next".
After clicking on NEXT, another window will appear. Choose the database table name as shown in the below screenshot and click "Finish".
Entity Framework gets added and the respective class gets generated under the Models folder.
Step 5
Right-click on Controllers folder add a controller.
A window will appear. Choose MVC5 Controller with views, using Entity Framework and click "Add".
After clicking on "Add", another window will appear. Choose the Model Class and data context class and click "Add". The EmployeesController will be added under the Controllers folder with respective views and views folder create details, edit and delete.
Modify Employees Controller Code
- using MvcRoleBasedAuthentication_Demo.Models;
- using System.Data.Entity;
- using System.Linq;
- using System.Net;
- using System.Web.Mvc;
-
- namespace MvcRoleBasedAuthentication_Demo.Controllers
- {
-
- public class EmployeesController : Controller
- {
- private EmployeeContext db = new EmployeeContext();
-
- [Authorize(Roles ="Admin,Employee")]
- public ActionResult Index()
- {
- var employees = db.Employees.Include(e => e.Department);
- return View(employees.ToList());
- }
-
- [Authorize(Roles = "Admin,Employee")]
- public ActionResult Details(int? id)
- {
- if (id == null)
- {
- return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
- }
- Employee employee = db.Employees.Find(id);
- if (employee == null)
- {
- return HttpNotFound();
- }
- return View(employee);
- }
-
- [Authorize(Roles = "Employee")]
- public ActionResult Create()
- {
- ViewBag.DepartmentId = new SelectList(db.Departments, "DeptId", "DepartmentName");
- return View();
- }
-
- [Authorize(Roles = "Employee")]
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Create([Bind(Include = "EmpId,Name,Gender,Age,Position,Office,HireDate,Salary,DepartmentId")] Employee employee)
- {
- if (ModelState.IsValid)
- {
- db.Employees.Add(employee);
- db.SaveChanges();
- return RedirectToAction("Index");
- }
-
- ViewBag.DepartmentId = new SelectList(db.Departments, "DeptId", "DepartmentName", employee.DepartmentId);
- return View(employee);
- }
-
- [Authorize(Roles = "Admin,Employee")]
- public ActionResult Edit(int? id)
- {
- if (id == null)
- {
- return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
- }
- Employee employee = db.Employees.Find(id);
- if (employee == null)
- {
- return HttpNotFound();
- }
- ViewBag.DepartmentId = new SelectList(db.Departments, "DeptId", "DepartmentName", employee.DepartmentId);
- return View(employee);
- }
-
- [Authorize(Roles = "Admin,Employee")]
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Edit([Bind(Include = "EmpId,Name,Gender,Age,Position,Office,HireDate,Salary,DepartmentId")] Employee employee)
- {
- if (ModelState.IsValid)
- {
- db.Entry(employee).State = EntityState.Modified;
- db.SaveChanges();
- return RedirectToAction("Index");
- }
- ViewBag.DepartmentId = new SelectList(db.Departments, "DeptId", "DepartmentName", employee.DepartmentId);
- return View(employee);
- }
-
- [Authorize(Roles = "Admin,Employee")]
- public ActionResult Delete(int? id)
- {
- if (id == null)
- {
- return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
- }
- Employee employee = db.Employees.Find(id);
- if (employee == null)
- {
- return HttpNotFound();
- }
- return View(employee);
- }
-
- [Authorize(Roles = "Admin,Employee")]
- [HttpPost, ActionName("Delete")]
- [ValidateAntiForgeryToken]
- public ActionResult DeleteConfirmed(int id)
- {
- Employee employee = db.Employees.Find(id);
- db.Employees.Remove(employee);
- db.SaveChanges();
- return RedirectToAction("Index");
- }
-
- protected override void Dispose(bool disposing)
- {
- if (disposing)
- {
- db.Dispose();
- }
- base.Dispose(disposing);
- }
- }
- }
Step 6
Right-click on Models folder and create a UserRoleProvider class.
UserRoleProvider Class
- using System;
- using System.Linq;
- using System.Web.Security;
-
- namespace MvcRoleBasedAuthentication_Demo.Models
- {
- public class UserRoleProvider : RoleProvider
- {
- public override string ApplicationName
- {
- get
- {
- throw new NotImplementedException();
- }
-
- set
- {
- throw new NotImplementedException();
- }
- }
-
- public override void AddUsersToRoles(string[] usernames, string[] roleNames)
- {
- throw new NotImplementedException();
- }
-
- public override void CreateRole(string roleName)
- {
- throw new NotImplementedException();
- }
-
- public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
- {
- throw new NotImplementedException();
- }
-
- public override string[] FindUsersInRole(string roleName, string usernameToMatch)
- {
- throw new NotImplementedException();
- }
-
- public override string[] GetAllRoles()
- {
- throw new NotImplementedException();
- }
-
- public override string[] GetRolesForUser(string username)
- {
- using (EmployeeContext _Context=new EmployeeContext())
- {
- var userRoles = (from user in _Context.Users
- join roleMapping in _Context.UserRoleMappings
- on user.Id equals roleMapping.UserId
- join role in _Context.Roles
- on roleMapping.RoleId equals role.Id
- where user.Username == username
- select role.RoleName).ToArray();
- return userRoles;
- }
- }
-
- public override string[] GetUsersInRole(string roleName)
- {
- throw new NotImplementedException();
- }
-
- public override bool IsUserInRole(string username, string roleName)
- {
- throw new NotImplementedException();
- }
-
- public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
- {
- throw new NotImplementedException();
- }
-
- public override bool RoleExists(string roleName)
- {
- throw new NotImplementedException();
- }
- }
- }
Step 7
Open web config file and write the following code.
- <authentication mode="Forms">
- <forms loginUrl="Account/Login"></forms>
- </authentication>
- <roleManager defaultProvider="userRoleProvider" enabled="true">
- <providers>
- <clear/>
- <add name="userRoleProvider" type="MvcRoleBasedAuthentication_Demo.Models.UserRoleProvider"/>
- </providers>
- </roleManager>
Step 8
Open _Layout.cshtml file under views folder in the shared folder. Add the following code into it.
- <nav class="navbar navbar-expand-md bg-dark navbar-dark">
- <a class="navbar-brand" href="#">
- @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
- </a>
- <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
- <span class="navbar-toggler-icon"></span>
- </button>
- <div class="collapse navbar-collapse" id="collapsibleNavbar">
- <ul class="navbar-nav">
- @if (User.Identity.IsAuthenticated)
- {
- <li class="nav-item">
- @Html.ActionLink("List", "Index", "Employees", new { @class = "nav-link" })
- </li>
- if (User.IsInRole("Admin") || User.IsInRole("Employee"))
-
- {
- <li class="nav-item">
- @Html.ActionLink("Add New", "Create", "Employees", new { @class = "nav-link" })
- </li>
- }
- <li class="nav-item">
- @Html.ActionLink("Hello ->" + @User.Identity.Name, "", "", new { @class = "nav-link" })
- </li>
- <li class="nav-item">
- @Html.ActionLink("Logout", "Logout", "Account", new { @class = "nav-link" })
- </li>
- }
- else
- {
- <li class="nav-item">
- @Html.ActionLink("Login", "Login", "Account", new { @class = "nav-link" })
- </li>
- }
- </ul>
- </div>
- </nav>
Step 9
Open Index.cshtm file and modify the code as below.
- @model IEnumerable<MvcRoleBasedAuthentication_Demo.Models.Employee>
-
- @{
- ViewBag.Title = "Index";
- }
-
- <h2>Index</h2>
-
- <p>
- @Html.ActionLink("Create New", "Create")
- </p>
- <table class="table table-bordered">
- <tr>
- <th>
- @Html.DisplayNameFor(model => model.Name)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Gender)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Age)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Position)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Office)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.HireDate)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Salary)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Department.DepartmentName)
- </th>
- <th>
- Action(s)
- </th>
- </tr>
-
- @foreach (var item in Model) {
- <tr>
- <td>
- @Html.DisplayFor(modelItem => item.Name)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Gender)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Age)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Position)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Office)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.HireDate)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Salary)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Department.DepartmentName)
- </td>
- <td>
- @if (User.IsInRole("Admin"))
- {
- @Html.ActionLink("Edit", "Edit", new { id = item.EmpId }, new { @class = "btn btn-sm btn-info" })
- @Html.ActionLink("Details", "Details", new { id = item.EmpId }, new { @class = "btn btn-sm btn-info" })
- }
-
- @Html.ActionLink("Delete", "Delete", new { id=item.EmpId }, new { @class = "btn btn-sm btn-danger" })
- </td>
- </tr>
- }
- </table>