
In this article we will see how to create and manage a User Role based Menu using ASP.NET MVC, WEB API and AngularJS.
Here we will see how to,
- Menu management by Admin (Only Admin user can View All / Create /Delete and Edit Menu).
- Create Menu by User Role (Admin can create menu by selecting User Role)
- Show and Hide Dynamic Menu and Sub Menu by User Role
- Dynamically Display Menu by User Role (Here we have mentioned as Dynamic menu as in every page or in Master Page we will be loading menu from data base and display the menu to each user by their role).
Why we need to create a Dynamic Menu
If we are working on a simple web site creation with very few pages and only one programmer is working to create a website then in that case we can create a static menu and use it in our web site.
Let's now consider we need to work for a big web application project. Let's consider development of an ERP Web application.
However if more than two developers are working and perhaps the number of pages is greater than 50 to 100 then it will be hard to maintain a static menu.
And also there will be a greater chance of removing and adding a new menu item to the web project, for example our client can ask to add 5 more new menus or remove 1 menu item.
In this case it will be a hard and difficult task to remove the menu items that are live now.
And also for large web projects like ERP we need to display the menu depending on the user roles. If we use a static menu then it will be very difficult to manage the users for the menu.
To avoid all this we create a Menu Management with a User Role setting.
Who can manage the Menu
This is a very important part since an Admin or Super user can Add/Edit/Delete a Menu.
When an Admin is logged in he can add a new menu, edit an existing menu and delete a menu item to be displayed.
In this article we will see in detail how to create a CRUD (Insert/Update/Select and Edit) Menu by Admin User and display the Admin created Menu to Logged In user by their Role using ASP.NET MVC, WEB API and AngularJS.
You can also view our previous article which explains how to display menu dynamically using MVC, AngularJS and WCF REST Service linkPrerequisites
Visual Studio 2015: You can download it from here.
Code partCreate Database and Table
This is in continuation of our previous article as we have told that ,we will be using a Common Database for both ASP.NET Identity tables and for our own new tables
In our previous article we have explained about creating User Role and during User registration user can select their Role.
Here for Role base Menu management we need to make a relationship table between ASP.NET Roles table and our menu table.
Let us see in detail about how to create our new Menu Table which has relationship with ASP.NET Identity AspNetRoles table.
Here we can see Field used for MenuMaster,

Here we can see Manager Role user Login and Menu displayed for Manager.

Here we can see Employee Role user Login and Menu displayed for Employee.

Menu Master Table and Stored Procedure for Menu CRUD operation
We will be using our existing database which we used in our previous article ASP.NET MVC 5 Security and Creating User Role (link above).
The following is the script to create a table, run this script in your SQL Server. I have used SQL Server 2014.
- USE AttendanceDB
- GO
- IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'MenuMaster' )
- DROP TABLE MenuMaster
- GO
- CREATE TABLE MenuMaster
- (
- MenuIdentity int identity(1,1),
- MenuID VARCHAR(30) NOT NULL,
- MenuName VARCHAR(30) NOT NULL,
- Parent_MenuID VARCHAR(30) NOT NULL,
- User_Roll [varchar](256) NOT NULL,
- MenuFileName VARCHAR(100) NOT NULL,
- MenuURL VARCHAR(500) NOT NULL,
- USE_YN Char(1) DEFAULT 'Y',
- CreatedDate datetime
- CONSTRAINT [PK_MenuMaster] PRIMARY KEY CLUSTERED
- (
- [MenuIdentity] ASC ,
- [MenuID] ASC,
- [MenuName] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- select * from MenuMaster
- -- 1) Stored procedure To Select all user roles
- -- Author : Shanu
- -- Create date : 2016-01-30
- -- Description :select all AspNetRoles all roll name to display in Combobox for menu creation.
- -- Tables used : AspNetRoles
- -- Modifier : Shanu
- -- Modify date : 2016-01-30
- -- =============================================
- -- To Select all user roles
- -- EXEC USP_UserRoles_Select ''
- -- =============================================
- CREATE PROCEDURE [dbo].[USP_UserRoles_Select]
- (
- @Rolename VARCHAR(30) = ''
- )
- AS
- BEGIN
- Select ID,Name
- FROM
- AspNetRoles
- WHERE
- Name like @Rolename +'%'
- END
- -- 2) Stored procedure To Select all Menu
- -- Author : Shanu
- -- Create date : 2016-01-30
- -- Description :select all MenuMaster detail
- -- Tables used : MenuMaster
- -- Modifier : Shanu
- -- Modify date : 2016-01-30
- -- =============================================
- -- To Select all menu master for Admin user.
- -- EXEC USP_Menu_Select '',''
- -- =============================================
- CREATE PROCEDURE [dbo].[USP_Menu_Select]
- (
- @MenuID VARCHAR(30) = '',
- @MenuName VARCHAR(30) = ''
- )
- AS
- BEGIN
- Select MenuIdentity ,
- MenuID ,
- MenuName ,
- Parent_MenuID ,
- User_Roll,
- MenuFileName ,
- MenuURL ,
- USE_YN ,
- CreatedDate
- FROM
- MenuMaster
- WHERE
- MenuID like @MenuID +'%'
- AND MenuName like @MenuName +'%'
- -- AND USE_YN ='Y'
- ORDER BY
- MenuName,MenuID
- END
- -- 3) Stored procedure To Select Menu by Logged in User Roll
- -- Author : Shanu
- -- Create date : 2016-01-30
- -- Description :select all AspNetRoles all roll name
- -- Tables used : AspNetRoles
- -- Modifier : Shanu
- -- Modify date : 2016-01-30
- -- =============================================
- -- To Select all user roles
- -- EXEC USP_MenubyUserRole_Select 'Admin'
- -- =============================================
- CREATE PROCEDURE [dbo].[USP_MenubyUserRole_Select]
- (
- @Rolename VARCHAR(30) = ''
- )
- AS
- BEGIN
- Select MenuIdentity ,
- MenuID ,
- MenuName ,
- Parent_MenuID ,
- User_Roll,
- MenuFileName ,
- MenuURL ,
- USE_YN ,
- CreatedDate
- FROM
- MenuMaster
- WHERE
- User_Roll = @Rolename
- AND USE_YN ='Y'
- ORDER BY
- MenuName,MenuID
- END
- -- 4) Stored procedure To Insert Menu
- -- Author : Shanu
- -- Create date : 2016-01-30
- -- Description :To Insert MenuMaster detail
- -- Tables used : MenuMaster
- -- Modifier : Shanu
- -- Modify date : 2016-01-30
- -- =============================================
- -- To Select all user roles
- -- =============================================
- CREATE PROCEDURE [dbo].[USP_Menu_Insert]
- (
- @MenuID VARCHAR(30) = '',
- @MenuName VARCHAR(30) = '',
- @Parent_MenuID VARCHAR(30) = '',
- @User_Roll VARCHAR(200) = '',
- @MenuFileName VARCHAR(100) = '',
- @MenuURL VARCHAR(500) = '',
- @USE_YN VARCHAR(1) = ''
- )
- AS
- BEGIN
- IF NOT EXISTS (SELECT * FROM MenuMaster WHERE MenuID=@MenuID and MenuName=@MenuName)
- BEGIN
- INSERT INTO MenuMaster
- ( MenuID , MenuName , Parent_MenuID , User_Roll, MenuFileName ,
- MenuURL , USE_YN , CreatedDate )
- VALUES ( @MenuID , @MenuName , @Parent_MenuID , @User_Roll, @MenuFileName ,
- @MenuURL , @USE_YN , GETDATE())
- Select 'Inserted' as results
- END
- ELSE
- BEGIN
- Select 'Exists' as results
- END
- END
- -- 5) Stored procedure To Update Menu
- -- Author : Shanu
- -- Create date : 2016-01-30
- -- Description :To Update MenuMaster detail
- -- Tables used : MenuMaster
- -- Modifier : Shanu
- -- Modify date : 2016-01-30
- -- =============================================
- -- To Select all user roles
- -- =============================================
- CREATE PROCEDURE [dbo].[USP_Menu_Update]
- ( @MenuIdentity Int=0,
- @MenuID VARCHAR(30) = '',
- @MenuName VARCHAR(30) = '',
- @Parent_MenuID VARCHAR(30) = '',
- @User_Roll VARCHAR(200) = '',
- @MenuFileName VARCHAR(100) = '',
- @MenuURL VARCHAR(500) = '',
- @USE_YN VARCHAR(1) = ''
- )
- AS
- BEGIN
- IF EXISTS (SELECT * FROM MenuMaster WHERE MenuIdentity=@MenuIdentity )
- BEGIN
- UPDATE MenuMaster SET
- MenuID=@MenuID,
- MenuName=MenuName,
- Parent_MenuID=@Parent_MenuID,
- User_Roll=@User_Roll,
- MenuFileName=@MenuFileName,
- MenuURL=@MenuURL,
- USE_YN=@USE_YN
- WHERE
- MenuIdentity=@MenuIdentity
- Select 'updated' as results
- END
- ELSE
- BEGIN
- Select 'Not Exists' as results
- END
- END
- -- 6) Stored procedure To Delete Menu
- -- Author : Shanu
- -- Create date : 2016-01-30
- -- Description :To Delete MenuMaster detail
- -- Tables used : MenuMaster
- -- Modifier : Shanu
- -- Modify date : 2016-01-30
- -- =============================================
- -- To Select all user roles
- -- =============================================
- Create PROCEDURE [dbo].[USP_Menu_Delete]
- ( @MenuIdentity Int=0 )
- AS
- BEGIN
- DELETE FROM MenuMaster WHERE MenuIdentity=@MenuIdentity
- END
As we have mentioned that this is in continues of our previous article. We will be using our existing project, which we used in our previous article you can download the source code.
Click Start, then Programs and select Visual Studio 2015 - Click Visual Studio 2015.
Click Open Project, go to your downloaded project folder and open the solution file.

Right click our project and click Add, then New Item. Select Data, then ADO.NET Entity Data Model and give the name for our EF and click,

Select "EF Designer from database" and click Next.

Here we no need to create a new Connection as we can use the existing connection which we used for our ASP.NET Identity User registration and Login. Click Next to select our Tables and Stored Procedure for Menu management.



Once the Entity has been created the next step is to add a Web API to our controller and write the function to Select/Insert/Update and Delete.
Procedure to add our Web API Controller
Right-click the Controllers folder, click Add and then click Controller.

Select Web API 2 Controller – Empty, click add and give name for our WEB API controller.

Here we are using our existing MVC project and we didn’t create the MVC Project with option selected as WEB API. So when we add a WEB API controller we can see the following readme text.

When we open Global.asax file we can see the System.Web.Http reference was been missing and also GlobalConfiguration was not been added in Application_Start .

- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Optimization;
- using System.Web.Routing;
- using System.Web.Http;
- namespace shanuMVCUserRoles
- {
- public class MvcApplication : System.Web.HttpApplication
- {
- protected void Application_Start()
- {
- AreaRegistration.RegisterAllAreas();
- GlobalConfiguration.Configure(WebApiConfig.Register);
- FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
- RouteConfig.RegisterRoutes(RouteTable.Routes);
- BundleConfig.RegisterBundles(BundleTable.Bundles);
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web.Http;
- namespace shanuMVCUserRoles
- {
- public static class WebApiConfig
- {
- public static void Register(HttpConfiguration config)
- {
- // Web API configuration and services
- // Web API routes
- config.MapHttpAttributeRoutes();
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- // routeTemplate: "api/{controller}/{id}",
- routeTemplate: "api/{controller}/{action}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- }
- }
- }
Select Controller and add an Empty Web API 2 Controller. Provide your name to the Web API controller and click OK. Here for my Web API Controller I have given the name “MenuAPIController ".
As we have created Web API controller, we can see our controller has been inherited with ApiController.
As we all know Web API is a simple and easy way to build HTTP Services for Browsers and Mobiles.
Web API has the following four methods as Get/Post/Put and Delete where:
- Get is to request for the data. (Select)
- Post is to create a data. (Insert)
- Put is to update the data.
- Delete is to delete data.
Get Method
In our example I have used only a Get method since I am using only a Stored Procedure. We need to create an object for our Entity and write our Get Method to do Select/Insert/Update and Delete operations.
Select Operation
We use a get method to get all the details of the MenuMasters table using an entity object and we return the result as IEnumerable. We use this method in our AngularJS and display the result in an MVC page from the AngularJS controller. Using Ng-Repeat we can bind the details.
Here we can see in the getMenuCRUDSelect method I have passed the search parameter to the USP_Menu_Select Stored Procedure. In the Stored Procedure I used like "%" to return all the records if the search parameter is empty.
- // to Search Menu Details and display the result
- [HttpGet]
- public IEnumerable<USP_Menu_Select_Result> getMenuCRUDSelect(string menuID, string menuName)
- {
- if (menuID == null)
- menuID = "";
- if (menuName == null)
- menuName = "";
- return objapi.USP_Menu_Select(menuID, menuName).AsEnumerable();
- }
- // To get all user role from ASPNETRoels Table
- [HttpGet]
- public IEnumerable<USP_UserRoles_Select_Result> getUserRoleDetails(string UserRole)
- {
- if (UserRole == null)
- UserRole = "";
- return objapi.USP_UserRoles_Select(UserRole).AsEnumerable();
- }
- // To get all Menu by User role to bind the menu dynamically in user pages
- [HttpGet]
- public IEnumerable<USP_MenubyUserRole_Select_Result> getMenubyUserRole(string UserRole)
- {
- if (UserRole == null)
- UserRole = "";
- return objapi.USP_MenubyUserRole_Select(UserRole).AsEnumerable();
- }
Insert Operation
The same as select we passed all the parameters to the insert procedure. This insert method will return the result from the database as a record is inserted or not. We will get the result and display it from the AngularJS Controller to MVC application.
- // To Insert new Menu Details
- [HttpGet]
- public IEnumerable<string> insertMenu(string menuID, string menuName, string parentMenuID, string UserRole, string menuFileName, string MenuURL, string UseYN)
- {
- return objapi.USP_Menu_Insert(menuID, menuName, parentMenuID, UserRole, menuFileName, MenuURL, UseYN).AsEnumerable();
- }
The same as Insert we have passed all the parameters to the Update procedure. This Update method will return the result from the database as a record is updated or not.
- //to Update Menu Details
- [HttpGet]
- public IEnumerable<string> updateMenu(int MenuIdentity, string menuID, string menuName, string parentMenuID, string UserRole, string menuFileName, string MenuURL, string UseYN)
- {
- return objapi.USP_Menu_Update(MenuIdentity, menuID, menuName, parentMenuID, UserRole, menuFileName, MenuURL, UseYN).AsEnumerable();
- }
The same as Insert we have passed all the parameters to the Delete procedure. This Delete method will return the result from the database as a record is delete or not.
- //to Delete Menu Details
- [HttpGet]
- public string deleteMenu(int MenuIdentity)
- {
- objapi.USP_Menu_Delete(MenuIdentity);
- objapi.SaveChanges();
- return "deleted";
- }
Firstly, create a folder inside the Scripts folder and we have given the folder name “MyAngular”.

Now add your Angular Controller inside the folder.
Right click the MyAngular folder and click Add and New Item. Select Web and then AngularJS Controller and provide a name for the Controller. I have named my AngularJS Controller “Controller.js”.

Once the AngularJS Controller is created, we can see by default the controller will have the code with the default module definition and all.
If the AngularJS package is missing, then add the package to your project.
Right click your MVC project and click Manage NuGet Packages. Search for AngularJS and click Install.

Modules.js: Here we will add the reference to the AngularJS JavaScript and create an Angular Module named “RESTClientModule”.
- // <reference path="../angular.js" />
- /// <reference path="../angular.min.js" />
- /// <reference path="../angular-animate.js" />
- /// <reference path="../angular-animate.min.js" />
- var app;
- (function () {
- app = angular.module("RESTClientModule", ['ngAnimate']);
- })();
1. Variable declarations
Firstly, we declared all the local variables need to be used.
- app.controller("AngularJs_Controller", function ($scope, $timeout, $rootScope, $window, $http) {
- $scope.date = new Date();
- $scope.MyName = "shanu";
- $scope.sMenuID = "";
- $scope.sMenuName = "";
- $scope.showMenuAdd = true;
- $scope.addEditMenu = false;
- $scope.MenuList = true;
- $scope.showItem = true;
- $scope.userRoleName = $("#txtuserRoleName").val();// this is hidden textbox which will be storing our logged in user Role Name.
- //This variable will be used for Insert/Edit/Delete menu details. menuID, menuName, parentMenuID, UserRole, menuFileName, MenuURL, UseYN
- $scope.MenuIdentitys = 0;
- $scope.menuIDs = "";
- $scope.menuNames = "";
- $scope.parentMenuIDs = "";
- $scope.selectedUserRole = "";
- $scope.menuFileNames = "";
- $scope.MenuURLs = "";
- $scope.UseYNs = true;
- $scope.searchRoleName = "";
Select Method
In the select method I have used $http.get to get the details from Web API. In the get method I will provide our API Controller name and method to get the details. Here we can see I have passed the search parameter of OrderNO and TableID using:
- { params: { menuID: menuID, menuName: menuName }
The final result will be displayed to the MVC HTML page using data-ng-repeat.
- //This method is used to search and display the Menu Details for display,Edit and Delete
- select MenuDetails($scope.sMenuID, $scope.sMenuName);
- function selectMenuDetails(menuID, menuName) {
- $http.get('/api/MenuAPI/getMenuCRUDSelect/', { params: { menuID: menuID, menuName: menuName } }).success(function (data) {
- $scope.MenuData = data;
- $scope.showMenuAdd = true;
- $scope.addEditMenu = false;
- $scope.MenuList = true;
- $scope.showItem = true;
- if ($scope.MenuData.length > 0) {
- }
- })
- .error(function () {
- $scope.error = "An Error has occured while loading posts!";
- });
- //Here we call all the created menu details to bind in select list for creating sub menu
- $http.get('/api/MenuAPI/getMenuCRUDSelect/', { params: { menuID: "", menuName: "" } }).success(function (data) {
- $scope.MenuDataSelect = data;
- })
- .error(function () {
- $scope.error = "An Error has occured while loading posts!";
- });
- }
- //Search
- $scope.searchMenuDetails = function () {
- selectMenuDetails($scope.sMenuID, $scope.sMenuName);
- }
- <table style="color:#9F000F;font-size:large" cellpadding="4" cellspacing="6">
- <tr>
- <td>
- <b>Menu ID</b>
- </td>
- <td>
- : <input type="text" name="txtMenuID" ng-model="sMenuID" value="" />
- <br />
- </td>
- <td>
- <b> Menu Name </b>
- </td>
- <td>
- :
- <input type="text" name="txtMenuName" ng-model="sMenuName" />
- </td>
- <td>
- <input type="submit" value="Search" style="background-color:#336699;color:#FFFFFF" ng-click="searchMenuDetails()" />
- </td>
- </tr>
- </table>

In the ADD/Edit menu Details button click we will make visible the MenuAdd table details where the Admin user can enter the new menu information. For a new Menu we will make the Menu ID as 0. In the New Menu save button click we will call the save method.
- // New Menu Add Details
- $scope.showMenuAddDetails = function () {
- cleardetails();
- $scope.showMenuAdd = true;
- $scope.addEditMenu = true;
- $scope.MenuList = true;
- $scope.showItem = true;
- }
For creating new menu Admin need to select User Role. For this we will bind all the ASP.NET Roles table all role details to the combobox .
AngularJS Conroller part:
Using our WEbAPI we get all the User Roles and store the result in $scope.userRoleData
- // This method is to get all the UserRole and bind to dropdownbox selection for creating menu by User Role.
- select userRoleDetails($scope.searchRoleName);
- // This method is to get all the UserRole and bind to dropdownbox selection for creating menu by User Role.
- function selectuerRoleDetails(UserRole) {
- $http.get('/api/MenuAPI/getUserRoleDetails/', { params: { UserRole: UserRole } }).success(function (data) {
- $scope.userRoleData = data;
- })
- rror(function () {
- $scope.error = "An Error has occured while loading posts!";
- ;
- }
Html part to bind Combobox with user roles
- <select name="opSelect" id="opSelect" ng-model="selectedUserRole">
- <option value="" selected>-- Select --</option>
- <option ng-repeat="option in userRoleData" value="{{option.Name}}">{{option.Name}}</option>
- </select>
Parent Menu ID bind to Combobox
For creating sub menu admin can select parent menu from ComboBox. Every time when admin create a Menu the main menu ID will be added to this combobox for creating sub menu.
AngularJS Conroller part:
Using our WEbAPI we get all the User Roles and store the result in $scope.userRoleData
Html part to bind Combobox with Parent Menu ID
- <select name="opSelect" id="opSelect" ng-model="parentMenuIDs">
- <option value="*" selected>*</option>
- <option ng-repeat="option in MenuDataSelect" value="{{option.MenuID}}">{{option.MenuID}}</option>
- </select>
- //Save Menu
- $scope.saveDetails = function () {
- if ($scope.selectedUserRole == "")
- {
- alert("Select User Role");
- return;
- }
- if ($scope.parentMenuIDs == "") {
- alert("Select parent ID");
- return;
- }
- $scope.IsFormSubmitted = true;
- if ($scope.IsFormValid) {
- if ($scope.UseYNs == true)
- {
- $scope.UseYNsN = "Y";
- }
- else
- {
- $scope.UseYNsN = "N";
- }
- //if the MenuIdentity ID=0 means its new Menu insert here i will call the Web api insert method
- if ($scope.MenuIdentitys == 0) {
- $http.get('/api/MenuAPI/insertMenu/', { params: { menuID: $scope.menuIDs, menuName: $scope.menuNames, parentMenuID: $scope.parentMenuIDs, UserRole: $scope.selectedUserRole, menuFileName: $scope.menuFileNames, MenuURL: $scope.MenuURLs, UseYN: $scope.UseYNsN } }).success(function (data) {
- $scope.menuInserted = data;
- alert($scope.menuInserted);
- cleardetails();
- selectMenuDetails('', '');
- selectMenubyUserRoleDetails($scope.userRoleName);
- })
- .error(function () {
- $scope.error = "An Error has occured while loading posts!";
- });
- }
- else { // to update to the Menu details
- $http.get('/api/MenuAPI/updateMenu/', { params: { MenuIdentity: $scope.MenuIdentitys, menuID: $scope.menuIDs, menuName: $scope.menuNames, parentMenuID: $scope.parentMenuIDs, UserRole: $scope.selectedUserRole, menuFileName: $scope.menuFileNames, MenuURL: $scope.MenuURLs, UseYN: $scope.UseYNsN } }).success(function (data) {
- $scope.menuUpdated = data;
- alert($scope.menuUpdated);
- cleardetails();
- selectMenuDetails('', '');
- selectMenubyUserRoleDetails($scope.userRoleName);
- })
- .error(function () {
- $scope.error = "An Error has occured while loading posts!";
- });
- }
- }
- else {
- $scope.Message = "All the fields are required.";
- }
- $scope.IsFormSubmitted = false;
- }

Let us login to our MVC application as Employee user and see how the new created menu is displayed.

Update Menu Master
Here again we logged in as Admin user for editing the newly created menu. Now we can see we can click on edit icon to edit the selected menu details. Now we will change the parent MenuID from ‘*’ to display the menu as sub menu of Employee Dashboard.


Now let’s see how to update the menu not to be visible for user. We login as Admin User and edit the Menu and uncheck the Menu Visible (Yes/No) checkbox and click save.



- //Delete Menu Detail
- $scope.MenuDelete = function MenuDelete(MenuIdentity, menuName) {
- cleardetails();
- $scope.MenuIdentitys = MenuIdentity;
- var delConfirm = confirm("Are you sure you want to delete the Student " + menuName + " ?");
- if (delConfirm == true) {
- $http.get('/api/MenuAPI/deleteMenu/', { params: { MenuIdentity: $scope.MenuIdentitys } }).success(function (data) {
- alert("Menu Deleted Successfully!!");
- cleardetails();
- selectMenuDetails('', '');
- })
- .error(function () {
- $scope.error = "An Error has occured while loading posts!";
- });
- }
- }
For display menu by user role we will pass the logged in user role to webAPI method to get all menu details for logged in user role users. In AngularJS controller we will get the logged in user role from hidden field and in our MVC page we will bind the logged in User role to hidden field.
- <input type="hidden" id="txtuserRoleName" value="@ViewBag.UserRole" />
- $scope.userRoleName = $("#txtuserRoleName").val();
- //********** ---------------- for Disoplay Menu by User Role ------------- ***************
- // This method is to get all the menu details of logged in users .Bind this result for creating Menu
- selectMenubyUserRoleDetails($scope.userRoleName);
- // This method is to get all the menu details of logged in users .Bind this result for creating Menu
- function selectMenubyUserRoleDetails(UserRole) {
- // alert($scope.userRoleName);
- $http.get('/api/MenuAPI/getMenubyUserRole/', { params: { UserRole: $scope.userRoleName } }).success(function (data) {
- $scope.generateMenuData = data;
- })
- .error(function () {
- $scope.error = "An Error has occured while loading posts!";
- });
- }
- $scope.showDetails = false;
- $scope.showSubDetails = false;
- $scope.subChildIDS = "";
- $scope.Imagename = "R1.png";
- $scope.showsubMenu = function (showMenus, ids) {
- if (showMenus == 1) {
- $scope.subChildIDS = ids;
- $scope.showSubDetails = true;
- }
- else if (showMenus == 0) {
- $scope.showSubDetails = false;
- }
- else {
- $scope.showSubDetails = true;
- }
- }
- //********** ---------------- End Disoplay Menu ------------- ***************
- <div style="overflow:visible;height:100px;">
- <ul class="menu">
- <li data-ng-repeat="menus in generateMenuData | filter:{Parent_MenuID:'*'}">
- @{var url = Url.Action("{{menus.MenuFileName}}", "{{menus.MenuURL}}", new { id = "{{id=menus.MenuURL}}" });
- url = HttpUtility.UrlDecode(url);
- }
- <a data-ng-href="@url">{{menus.MenuName}}</a>
- <ul class="sub-menu">
- <li data-ng-repeat="submenus in generateMenuData | filter:{Parent_MenuID:menus.MenuID}" ng-mouseover="showsubMenu(1,submenus.MenuID);" ng-mouseout="showsubMenu(0,submenus.MenuID);">
- @{var url1 = Url.Action("{{submenus.MenuFileName}}", "{{submenus.MenuURL}}", new { id = "{{id=submenus.MenuURL}}" });
- url1 = HttpUtility.UrlDecode(url1);
- }
- <a data-ng-href="@url1">{{submenus.MenuName}}</a>
- <ul ng-show="showSubDetails" class="sub-menu2">
- <li data-ng-repeat="sub1menus in generateMenuData | filter:{Parent_MenuID:submenus.MenuID}" ng-mouseover="showsubMenu(3,9);">
- @{var url2 = Url.Action("{{sub1menus.MenuFileName}}", "{{sub1menus.MenuURL}}", new { id = "{{id=sub1menus.MenuURL}}" });
- url2 = HttpUtility.UrlDecode(url2);
- }
- <a data-ng-href="@url2">{{sub1menus.MenuName}}</a>
- </li>
- </ul>
- </li>
- </ul>
- </li>
- </ul>
- </div>
In MVC Controller we check for Authentication and Authorization. Only logged in user can view this page and in controller we check for each user role and pass the role from Controller to View to display the menu by user role.
- public string RoleName { get; set; }
- // GET: Users
- public ActionResult Index()
- {
- if (User.Identity.IsAuthenticated)
- {
- var user = User.Identity;
- ViewBag.Name = user.Name;
- ApplicationDbContext context = new ApplicationDbContext();
- var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
- var s = UserManager.GetRoles(user.GetUserId());
- RoleName = s[0].ToString();
- ViewBag.displayMenu = "No";
- ViewBag.UserRole = RoleName;
- if (RoleName == "Admin")
- {
- ViewBag.displayMenu = "Yes";
- }
- return View();
- }
- else
- {
- return RedirectToAction("Index", "Home");
- }
- }
Firstly, run all the script to your SQL Server you can also find the SQL Script file from attached zip file. After your download the source code kindly change the Web.Config file DefaultConnection connection string with your SQL Server Connections. In Startup.cs file we have created default Admin user with UserName "shanu" and password "A@Z200711." This UserName and password will be used to login as Admin user. You can change this user name and password as you like. For security reasons after logging in as Admin you can change the Admin user password as you like.

BlackPosted Apr 5, 2024, 7:03 PM
Thanks for your cool project ! I will be appreciated that if we can add multiple role to one menu
pravati santaraPosted Apr 4, 2018, 8:41 AM
I am not bale to run the application when i am runing its taking my domain name and saying logined fail for userid .Please help .An exception of type 'System.Data.SqlClient.SqlException' occurred in mscorlib.dll but was not handled in user codeAdditional information: Login failed for user:-----Domain\Usernamexxxxxxxx
Juan LopezPosted Mar 8, 2017, 7:00 AM
How many stored procedures are in total? because in code you are calling two diferents stored procedures "USP_MenubyUserRol_Select" and USP_MenubyUserRoll_Select and those are diferent in one letter l . in the database script that you posted are only six stored... what is wrong ?? Application fire an exception when USP_MenubyUserRol_Select is called. Thanks for this article is great but I have that problem :/
Prateek JasoriyaPosted Mar 6, 2017, 3:28 AM
Really appreciated your work on dynamic menu... Just a quick query...how to have access single menu for multiple roles
Md Ilyas Hasan MamunPosted Jul 23, 2016, 5:22 AM
Really appreciable work. If # is present in the angularjs url of an asp.net mvc5 project,for example http://localhost:4137/#/Transaction/Index, how can I be able to manage the menu url?
Amol SalunkePosted Apr 16, 2016, 5:49 AM
Really helpful.. for me thanks..
RubolPosted Feb 4, 2016, 6:08 AM
Nice
Humayun Kabir MamunPosted Feb 3, 2016, 11:15 PM
Nice...
Sibeesh VenuPosted Feb 2, 2016, 4:05 AM
Such a long article. Really appreciate your hard work. Nice read.
Ankit BansalPosted Feb 2, 2016, 12:03 AM
You are great Syed..I liked your customized approaches..
Debasis SahaPosted Feb 1, 2016, 11:43 PM
Nice article...
Jaipal ReddyPosted Feb 1, 2016, 10:57 PM
Thanks for sharing . .
Mohammed IbrahimPosted Feb 1, 2016, 2:06 PM
nice
Santhakumar MunuswamyPosted Feb 1, 2016, 12:15 PM
Good work. Keep it up
Shashangka ShekharPosted Feb 1, 2016, 11:21 AM
Nice share, Thanks