Friday, August 9, 2019

Creating dynamic menu from database data using AngularJS

Just follow the following steps in order implement multi-level navigation menu with AngularJS

Here In this article, I have used Visual Studio 2013 

Step-1: Create New Project.

Go to File > New > Project > ASP.NET  Web Application (under web) > Entry Application Name > Click OK > Select Empty template > Checked MVC (under "Add folders and core references for" option) > OK

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create a table for store menu data.

In this example, I have used 1 table as below, where I have added ParentID column in our table to hold Parent and child relationships between the menus.

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >


Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Create a javascript file for angular components.

Here I have created a folder named "Scripts" first, and then I have added a javascript file for add angular components (module, controller etc). Here we will fetch menu data from the database.
Right Click on your solution file (from solution explorer) > Add > New Folder > Renamed your folder. and then
Right click on your folder (just created) > Add > New Item > select "javascript" file > Enter name (here "MyApp.js")> Ok.
Write following code 
  1. var app = angular.module('MyApp', []);
  2. app.controller('menuController', ['$scope', '$http', function ($scope, $http) {
  3. $scope.SiteMenu = [];
  4. $http.get('/home/GetSiteMenu').then(function (data) {
  5. $scope.SiteMenu = data.data;
  6. }, function (error) {
  7. alert('Error');
  8. })
  9. }])

Step-6: Create a CSS file for styling navigation menu.

Now we will create a CSS file for styling the navigation menu. Here in this example, our menu will be a multi-level menu.
In the same way, first I have added a folder named "css" and then added a CSS file.
Right Click on your solution file (from solution explorer) > Add > New Folder > Renamed your folder. and then
Right click on your folder (just created) > Add > New Item > select "style sheet" file > Enter name (here "navMenu.css") > Ok.
Write following code 
  1. /*Here I will write css for show horizantal nav menu*/
  2. ul {
  3. list-style: none;
  4. padding: 0;
  5. margin: 0;
  6. background: #1bc2a2;
  7. }
  8.  
  9. ul li {
  10. display: block;
  11. position: relative;
  12. float: left;
  13. background: #1bc2a2;
  14. }
  15. li ul { display: none; }
  16.  
  17. ul li a {
  18. display: block;
  19. padding: 1em;
  20. text-decoration: none;
  21. white-space: nowrap;
  22. color: #fff;
  23. }
  24.  
  25. ul li a:hover { background: #2c3e50; }
  26. li:hover > ul {
  27. display: block;
  28. position: absolute;
  29. }
  30.  
  31. li:hover li { float: none; }
  32.  
  33. li:hover a { background: #1bc2a2; }
  34.  
  35. li:hover li a:hover { background: #2c3e50; }
  36.  
  37. .main-navigation li ul li { border-top: 0; }
  38. ul ul ul {
  39. left: 100%;
  40. top: 0;
  41. }
  42. ul:before,
  43. ul:after {
  44. content: " "; /* 1 */
  45. display: table; /* 2 */
  46. }
  47. ul:after { clear: both; }

Step-7: Create a Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Here I have created a controller named "HomeController"

Step-8: Add new action into your controller for getting the view, where we will show navigation menu

It should be in the Layout page, but I have shown here in the Index page for making the post simple to understand. 
Here I have added "Index" Action into "Home" Controller. Please write this following code
  1. public ActionResult Index()
  2. {
  3. return View();
  4. }

Step-9: Add view for your Action & design for show multi-level navigation menu.

Right Click on Action Method (here right click on Index action) > Add View... > Enter View Name > Select View Engine (Razor) > Add.
HTML Code 
  1. @{
  2. ViewBag.Title = "Index";
  3. }
  4. <h2>Dynamic menu from database in AngularJS</h2>
  5. @* Html code for show nav menu here, for mak the application simple
  6. I will add ngapp and ngcontroller here *@
  7. <div ng-app="MyApp">
  8. <div ng-controller="menuController">
  9. @* Here first of all we will create a ng-template *@
  10. <script type="text/ng-template" id="treeMenu">
  11. <a href="{{menu.Url}}">{{menu.Name}}</a>
  12. @* We will create submenu only when available *@
  13. <ul ng-if="(SiteMenu | filter:{ParentID : menu.ID}).length > 0">
  14. @*<li ng-repeat="menu in SiteMenu | filter:{ParentID : menu.ID}" ng-include="'treeMenu'"></li>*@
  15. <li ng-repeat="menu in SiteMenu | filter:{ParentID : menu.ID} : true" ng-include="'treeMenu'"></li>
  16. </ul>
  17. </script>
  18. <ul class="main-navigation">
  19. @* Here we will load only top level menu *@
  20. @*<li ng-repeat="menu in SiteMenu | filter:{ParentID : 0}" ng-include="'treeMenu'"></li>*@
  21. <li ng-repeat="menu in SiteMenu | filter:{ParentID : 0} : true" ng-include="'treeMenu'"></li>
  22. </ul>
  23. </div>
  24. </div>
  25. @* Add css here for nav menu *@
  26. <link href="~/css/navMenu.css" rel="stylesheet" />
  27.  
  28. @* add js here for angular app *@
  29. @section Scripts{
  30. <script src="~/Scripts/MyApp.js"></script>
  31. }
Here you can see, I have used ng-include directive for including templates/HTML fragments.

Step-10: Add an another action into your controller for getting menu data from database

  1. public JsonResult GetSiteMenu()
  2. {
  3. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  4. {
  5. var menu = dc.SiteMenus.ToList();
  6. return new JsonResult { Data = menu, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
  7. }
  8. }

Step-11: Modify _Layout.cshtml page for load AngularJS library

_Layout.cshtml HTML Code 
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>@ViewBag.Title - My ASP.NET Application</title>
  7. <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
  8. <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
  9. <script src="~/Scripts/modernizr-2.6.2.js"></script>
  10. </head>
  11. <body>
  12. <div class="container body-content">
  13. @RenderBody()
  14. <hr />
  15. <footer>
  16. <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
  17. </footer>
  18. </div>
  19.  
  20. <script src="~/Scripts/jquery-1.10.2.min.js"></script>
  21. <script src="~/Scripts/bootstrap.min.js"></script>
  22. <!--HERE we will add angular.js library-->
  23. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
  24. @RenderSection("Scripts", false)
  25. </body>
  26. </html>

1 comment:

  1. Interesting and amazing how your post is! It Is Useful and helpful for me That I like it very much, and I am looking forward to Hearing from your next..
    architectactionresult

    ReplyDelete

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...