Dynamic Menu Generation With Web API And Angular

Introduction

In this article, we are going to implement dynamic menu with the help of ASP.NET Web API and Angular JS.

We will create the login page that has two login types - Admin and User.

Admin login will lead to some different menu items and User login will come up with different menu items.

Prerequisite

  1. Programming of C#.
  2. Knowledge of JavaScript or AngularJS.

Implementation.

Open Visual Studio.

Angular

Angular

Select ASP.NET Web Application, give the name of the solution, and click OK.

Create a class file, Menu.cs, inside Models folder.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace CustomMenuDemo.Models  
  7. {  
  8.     public class Menu  
  9.     {  
  10.         List<Menu> MenuList;  
  11.         public int MenuId { get; set; }  
  12.         public string MenuName { get; set; }  
  13.         public string MenuHref { get; set; }  
  14.         public List<Menu> GetMenu(int id)  
  15.         {  
  16.             MenuList = new List<Menu>();  
  17.             if (id == 1)  
  18.             {  
  19.                 MenuList.Add(new Menu() { MenuId = 1, MenuName = "Add Employee", MenuHref="#" });  
  20.                 MenuList.Add(new Menu() { MenuId = 2, MenuName = "View Employee", MenuHref = "#" });  
  21.                 MenuList.Add(new Menu() { MenuId = 3, MenuName = "Delete Employee", MenuHref = "#" });  
  22.                 MenuList.Add(new Menu() { MenuId = 4, MenuName = "Edit Employee", MenuHref = "#" });  
  23.                 MenuList.Add(new Menu() { MenuId = 5, MenuName = "Logout", MenuHref = "#" });  
  24.             }  
  25.             else  
  26.             {  
  27.                 MenuList.Add(new Menu() { MenuId = 1, MenuName = "Edit Details", MenuHref = "#" });  
  28.                 MenuList.Add(new Menu() { MenuId = 2, MenuName = "My Task", MenuHref = "#" });  
  29.                 MenuList.Add(new Menu() { MenuId = 3, MenuName = "Contact Us", MenuHref = "#" });  
  30.                 MenuList.Add(new Menu() { MenuId = 4, MenuName = "Logout", MenuHref = "#" });  
  31.             }  
  32.             return MenuList;  
  33.         }  
  34.     }  
  35. }  

Add a Controller file inside Controllers folder.

Angular

Give it a name as MenuController.

Angular

Add the Controller class. Modify the content as below.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using CustomMenuDemo.Models;  
  8.   
  9. namespace CustomMenuDemo.Controllers  
  10. {  
  11.   
  12.     public class MenuController : ApiController  
  13.     {  
  14.         // GET api/Menu  
  15.         public IEnumerable<string> Get()  
  16.         {  
  17.             return new string[] { "value1""value2" };  
  18.         }  
  19.   
  20.         // GET api/Menu/5  
  21.         public List<Menu> Get(int id)  
  22.         {  
  23.             return new Menu().GetMenu(id);  
  24.         }  
  25.   
  26.         // POST api/Menu  
  27.         public void Post([FromBody]string value)  
  28.         {  
  29.         }  
  30.   
  31.         // PUT api/Menu/5  
  32.         public void Put(int id, [FromBody]string value)  
  33.         {  
  34.         }  
  35.   
  36.         // DELETE api/Menud/5  
  37.         public void Delete(int id)  
  38.         {  
  39.         }  
  40.     }  
  41. }  

Create App/js folder inside Content directory.

Add index.js file with the following content.

  1. var myapp = angular.module('uirouteApp', ["ui.router"]);  
  2. myapp.config(function ($stateProvider) {  
  3.     $stateProvider  
  4.         .state('index', {  
  5.             url: "",  
  6.             views: {  
  7.                   
  8.             }  
  9.         })  
  10.         .state('Home', {  
  11.             url: "/Home",  
  12.             views: {  
  13.                 "secondView": {  
  14.                     template: "<span class='category-note'>Logged in Successfully!</span>"  
  15.                 }  
  16.             }  
  17.         })  
  18. });  
  19.   
  20. myapp.controller('LoginController'function ($scope, $rootScope, $stateParams, $state, $http, LoginService, MenuService, UserService) {  
  21.     $rootScope.title = "AngularJS Login Sample";  
  22.     $scope.menus = [{ "MenuId": 1, "MenuName""Home""MenuHref""#" }, { "MenuId": 2, "MenuName""Contact Us""MenuHref""#" }];  
  23.     $scope.username = '';  
  24.     $scope.password = '';  
  25.     $scope.usertype = '';  
  26.     $scope.formSubmit = function (username, password, usertype) {  
  27.         $scope.username = username;  
  28.         $scope.password = password;  
  29.         $scope.usertype = usertype;  
  30.         if (LoginService.login($scope.username, $scope.password, $scope.usertype)) {  
  31.             $http({  
  32.                 method: "GET",  
  33.                 url: "http://localhost:54824/api/Menu/" + $scope.usertype  
  34.             }).then(function mySuccess(response) {  
  35.                 $scope.menus = response.data;  
  36.                 UserService.setUser({  
  37.                     username: $scope.username,  
  38.                     password: $scope.password,  
  39.                     usertype: $scope.usertype  
  40.                 });  
  41.                 $scope.$apply();  
  42.                 $state.go("Home")  
  43.             }, function myError(response) {  
  44.                 $scope.message = response.statusText;  
  45.             });  
  46.             $scope.error = '';  
  47.             $scope.username = '';  
  48.             $scope.password = '';  
  49.             //$state.transitionTo('home');  
  50.         } else {  
  51.             $scope.error = "Incorrect username/password !";  
  52.         }  
  53.     };  
  54.   
  55. });  
  56.   
  57. myapp.factory('LoginService'function ($http) {  
  58.     var isAuthenticated = false;  
  59.     var menus = null;  
  60.   
  61.     return {  
  62.         login: function (username, password, type) {  
  63.             // fields validation check here  
  64.             return true;  
  65.         },  
  66.         isAuthenticated: function () {  
  67.             return isAuthenticated;  
  68.         }  
  69.     };  
  70.   
  71. });  
  72.   
  73. myapp.service('MenuService'function () {  
  74.   
  75.     var menus = {};  
  76.     this.save = function (m) {  
  77.         this.menus = m;  
  78.   
  79.     };  
  80.   
  81.     this.getMenus = function () {  
  82.   
  83.         return this.menus;  
  84.   
  85.     };  
  86. });  
  87.   
  88. myapp.service('UserService'function () {  
  89.   
  90.     var user =  
  91.         {  
  92.             username: "",  
  93.             password: "",  
  94.             usertype: ""  
  95.         };  
  96.     this.setUser = function (u) {  
  97.         this.user = u;  
  98.   
  99.     };  
  100.   
  101.     this.getUser = function () {  
  102.   
  103.         return this.user;  
  104.   
  105.     };  
  106. });  

Open Index.cshtml from Home View and add the below content.

  1. <script src='http://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js'></script>  
  2. <script src='http://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.12.0/ui-bootstrap-tpls.min.js'></script>  
  3. <script src='http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.13/angular-ui-router.min.js'></script>  
  4. <script src="~/Content/App/js/index.js"></script>  
  5. <div class="container" ng-app="uirouteApp" ng-controller="LoginController">  
  6.     <header class="projects">  
  7.         <h1 class="projects-title">Dynamic Menu:</h1>  
  8.     </header>  
  9.     <section class="projects">  
  10.         <div class="wrapper">  
  11.             <div class="row">  
  12.                 <div class="col-md-3" ui-view="firstView">  
  13.                     <div>  
  14.                         <p ng-repeat="item in menus"><a href="{{item.MenuHref}}"> {{item.MenuName}}</a></p>  
  15.                     </div>  
  16.                 </div>  
  17.                 <div class="col-md-9" ui-view="secondView">  
  18.                     <h3>Login Page</h3>  
  19.                     <form class="form">  
  20.                             <div class="form-group">  
  21.                                 <input type="text" class="form-control" ng-model="username" placeholder="username" required="" />  
  22.                             </div>  
  23.                             <div class="form-group">  
  24.                                 <input type="password" class="form-control" ng-model="password" placeholder="password" required="" />  
  25.                             </div>  
  26.                             <div class="radio">  
  27.                                 <label><input type="radio" ng-value="1" ng-model="usertype" name="optradio">Admin</label>  
  28.                             </div>  
  29.                             <div class="radio disabled">  
  30.                                 <label><input type="radio" ng-value="2" ng-model="usertype" name="optradio">User</label>  
  31.                             </div>  
  32.                             <div class="form-group">  
  33.                                 <button type="button" class="btn btn-success" ng-click="formSubmit(username, password, usertype)">Login</button>  
  34.                                 <span class="text-danger">{{ error }}</span>  
  35.                             </div>  
  36.                     </form>  
  37.                 </div>  
  38.             </div>  
  39.         </div>  
  40.     </section>  
  41. </div>  

Open Layout.cshtml from shared View and edit it with the below content.

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <meta name="viewport" content="width=device-width" />  
  6.     <meta charset="UTF-8">  
  7.     <title>Custom Menu</title>  
  8.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  9.     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">  
  10.     <link rel='stylesheet prefetch' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css'>  
  11.     <title>@ViewBag.Title</title>  
  12.     @Styles.Render("~/Content/css")  
  13.     @Scripts.Render("~/bundles/modernizr")  
  14. </head>  
  15. <body style="background-color: #d1cccd">  
  16.     @RenderBody()  
  17.     @Scripts.Render("~/bundles/jquery")  
  18.     @Scripts.Render("~/bundles/bootstrap")  
  19.     @RenderSection("scripts", required: false)  
  20. </body>  
  21. </html>  

The directory structure will be as follows.

Angular

Build and run the application.

Angular

Give username and password and select Admin.

Angular

Click "Login".

Angular

Now, click on Logout and check for User.

Angular

Give username and password and click "Login".

Angular

Note - This application only demonstrate how can we achieve the custom menu through Web API and AngularJS. You can get the menu values from the database unlike in this application the direct sending of menu information. You can define different Views based on the user or menu item. You can perform login check defined inside its service in index.js. You can do validation also.

You may need to change the URL "http://localhost:54824/api/Menu/" based on your server port.