banner



How To Create Menu And Submenu In Mvc 5

  • Updated date Jan 05, 2021
  • 139k
  • 6

Many times we need to create a menu for a simple application. We ususally get stuck on how to bind the menu. Here in this article we you will learn how to bind menu and sub menu dynamically in ASP.NET MVC from database using linq.

Introduction

Many times we need to create a menu for a simple application. We ususally get stuck on how to bind the menu. Here in this article we you will learn how to bind menu and sub menu dynamically in ASP.NET MVC from database using linq.

Source code is upload here.

Note below points,

Please take care about the variable names As in article I have used,

  • M_ID instade of M_CODE
  • M_P_ID insatde of M_PARENT_CODE

Change the web config setting as per your SQL Connection.

Step 1

I am going to create a database which contains the following fields as well as some dummy data which contains parent & child relationship.

Use the below script to create table & insert query,

  1. USE [Dynamic_Menu]
  2. GO
  3. SET  ANSI_NULLS ON
  4. GO
  5. SET  QUOTED_IDENTIFIER ON
  6. GO
  7. SET  ANSI_PADDING ON
  8. GO
  9. CREATE TABLE  [dbo].[Menu_List](
  10.     [M_ID] [int ] IDENTITY(1,1) NOT NULL ,
  11.     [M_P_ID] [int ] NULL ,
  12.     [M_NAME] [varchar ](50) NULL ,
  13.     [CONTROLLER_NAME] [varchar ](50) NULL ,
  14.     [ACTION_NAME] [varchar ](50) NULL ,
  15. CONSTRAINT  [PK_Menu_List] PRIMARY KEY  CLUSTERED
  16. (
  17.     [M_ID]ASC
  18. )WITH  (PAD_INDEX  = OFF , STATISTICS_NORECOMPUTE  = OFF , IGNORE_DUP_KEY = OFF , ALLOW_ROW_LOCKS  = ON , ALLOW_PAGE_LOCKS  = ON ) ON  [ PRIMARY ]
  19. )ON  [ PRIMARY ]
  20. GO
  21. SET  ANSI_PADDING OFF
  22. GO
  23. SET  IDENTITY_INSERT [dbo].[Menu_List] ON
  24. INSERT  [dbo].[Menu_List] ([M_ID], [M_P_ID], [M_NAME], [CONTROLLER_NAME], [ACTION_NAME]) VALUES  (1, 0, N 'My Menu' , NULL , NULL )
  25. INSERT  [dbo].[Menu_List] ([M_ID], [M_P_ID], [M_NAME], [CONTROLLER_NAME], [ACTION_NAME]) VALUES  (2, 1, N 'BCS' , N 'Menu' , N 'BCS_Action' )
  26. INSERT  [dbo].[Menu_List] ([M_ID], [M_P_ID], [M_NAME], [CONTROLLER_NAME], [ACTION_NAME]) VALUES  (3, 2, N 'Computer' , N 'Menu' , N 'Computer_Action' )
  27. INSERT  [dbo].[Menu_List] ([M_ID], [M_P_ID], [M_NAME], [CONTROLLER_NAME], [ACTION_NAME]) VALUES  (4, 1, N 'MCS' , N 'Menu' , N 'MCS_Action' )
  28. INSERT  [dbo].[Menu_List] ([M_ID], [M_P_ID], [M_NAME], [CONTROLLER_NAME], [ACTION_NAME]) VALUES  (5, 2, N 'Maths' , N 'Menu' , N 'Maths_Action' )
  29. INSERT  [dbo].[Menu_List] ([M_ID], [M_P_ID], [M_NAME], [CONTROLLER_NAME], [ACTION_NAME]) VALUES  (6, 4, N 'Marketing' , N 'Menu' , N 'Marketing_Action' )
  30. INSERT  [dbo].[Menu_List] ([M_ID], [M_P_ID], [M_NAME], [CONTROLLER_NAME], [ACTION_NAME]) VALUES  (7, 4, N 'Finiance' , N 'Menu' , N 'Finiance_Action' )
  31. SET  IDENTITY_INSERT [dbo].[Menu_List] OFF

Step 2Now create simple MVC appliation using visual studio. After creating project add edmx file by right clicking on project go to Add => New Item => (from right side templates) select Data => Select ADO.NET Entity Data Model => Give proper name to it and click on add button.

Then select your table from database & create .edmx file into your ptoject. After adding the file autmatically connection string will get added into web config file.

Step 3Now create model as below and add some properties; this model will be used into a controller & view.

  1. using  System;
  2. using  System.Collections.Generic;
  3. using  System.Linq;
  4. using  System.Web;
  5. namespace  Dynamic_Menu.Models
  6. {
  7. public class  Menu_List
  8.     {
  9. public int  M_ID { get ; set ; }
  10. public int ? M_P_ID { get ; set ; }
  11. public string  M_NAME { get ; set ; }
  12. public string  CONTROLLER_NAME { get ; set ; }
  13. public string  ACTION_NAME { get ; set ; }
  14.     }
  15. }

Step 4Now add controller into our application and write below code into it. From action method GetMenuList() we will get data from our database using linq query.

  1. using  System;
  2. using  System.Collections.Generic;
  3. using  System.Linq;
  4. using  System.Web;
  5. using  System.Web.Mvc;
  6. namespace  Dynamic_Menu.Controllers
  7. {
  8. public class  HomeController : Controller
  9.     {
  10.         MenuEntities objEntity =new  MenuEntities();
  11. public  ActionResult Index()
  12.         {
  13. return  View();
  14.         }
  15. public  ActionResult GetMenuList()
  16.         {
  17. try
  18.             {
  19.                 var result = (from min  objEntity.Menu_Tree
  20.                               selectnew  Dynamic_Menu.Models.Menu_List
  21.                               {
  22.                                   M_ID = m.M_ID,
  23.                                   M_P_ID = m.M_P_ID,
  24.                                   M_NAME = m.M_NAME,
  25.                   CONTROLLER_NAME = CONTROLLER_NAME,
  26.                                   ACTION_NAME = ACTION_NAME,
  27.                               }).ToList();
  28. return  View( "Menu" , result);
  29.             }
  30. catch  (Exception ex)
  31.             {
  32.                 var error = ex.Message.ToString();
  33. return  Content( "Error" );
  34.             }
  35.         }
  36.     }
  37. }

Step 5

Now create a view for Index action method as like.

  1. @{
  2. ViewBag.Title  = "Index" ;
  3. Layout  = "~/Views/Shared/_Layout.cshtml" ;
  4. }
  5. < h2 > Index </ h2 >

Now create layout view for our application. Also create one partial view (name Menu.cshtml) as brlow,  which will render menu tree list when we are going to call action method from our layout page. In this partial view we are getting data into a IEnumerable list format and we are applying some logic as below,

Note

This is just demo / sample application, according to your requirement you can add foreach loop for more hierarchy levels. This is only a two level menu tree strucure.

_Layout.cshtml =>

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <meta name="viewport"  content= "width=device-width"  />
  5.     <title>@ViewBag.Title</title>
  6.     @Html.Action("GetMenuList" , "Home" )
  7. </head>
  8. <body>
  9.     <div>
  10.         @RenderBody()
  11.     </div>
  12. </body>
  13. </html>

Menu.cshtml =>

  1. @model IEnumerable<Dynamic_Menu.Models.Menu_List>
  2. <div>
  3.     <ul>
  4.         @{foreach (var  item in  Model.Where(s => s.M_P_ID == 0).GroupBy(Obj => new  { Obj.M_ID }).Distinct().ToList())
  5.         {
  6.             <li>
  7.                 <a href="#" >
  8.                     @item.FirstOrDefault().M_NAME
  9.                 </a>
  10.                 <ul>
  11.                     @{foreach (var  firstItem in  (Model.Where(s => s.M_P_ID == item.FirstOrDefault().M_ID).ToList()))
  12.                     {
  13.                         <li>
  14.                             <a href="#" >
  15.                                 @firstItem.M_NAME
  16.                             </a>
  17.                             <ul>
  18.                                 @foreach (var  secondItem in  (Model.Where(s => s.M_P_ID == firstItem.M_ID).ToList()))
  19.                                 {
  20.                                     <li>
  21.                                         <a href="/@secondItem.CONTROLLER_NAME/@secondItem.ACTION_NAME" >
  22.                                             @secondItem.M_NAME
  23.                                         </a>
  24.                                     </li>
  25.                                 }
  26.                             </ul>
  27.                         </li>
  28.                     }
  29.                     }
  30.                 </ul>
  31.             </li>
  32.         }
  33.         }
  34.     </ul>
  35. </div>

Step 5

Now create another controller to render views whenever we are clicking on hyper links from menu, it will redirect to that view by using controller name & action name

  1. namespace  Dynamic_Menu.Controllers
  2. {
  3. public class  MenuController : Controller
  4.     {
  5.         public  ActionResult Computer_Action()
  6.         {
  7. return  View();
  8.         }
  9. public  ActionResult Maths_Action()
  10.         {
  11. return  View();
  12.         }
  13. public  ActionResult Marketing_Action()
  14.         {
  15. return  View();
  16.         }
  17. public  ActionResult Finiance_Action()
  18.         {
  19. return  View();
  20.         }
  21.      }
  22. }

Create some views for above action as like

View For Computer_Action as,

  1. @{
  2.     Layout ="~/Views/Shared/_Layout.cshtml" ;
  3. }
  4. <!DOCTYPE html>
  5. <html>
  6. <head>
  7.     <meta name="viewport"  content= "width=device-width"  />
  8.     <title>Computer_Action</title>
  9. </head>
  10. <body>
  11.     <div>
  12.         <h2>Welcome To Computer View</h2>
  13.     </div>
  14. </body>
  15. </html>

View For MCS_Action as

  1. @{
  2.     Layout ="~/Views/Shared/_Layout.cshtml" ;
  3. }
  4. <!DOCTYPE html>
  5. <html>
  6. <head>
  7.     <meta name="viewport"  content= "width=device-width"  />
  8.     <title>MCS_Action</title>
  9. </head>
  10. <body>
  11.     <div>
  12.         <h2>Welcome To MCS View</h2>
  13.     </div>
  14. </body>
  15. </html>

Step 6 Now run the application.

Index view after running the application into a browser.


If we click on menu   then our output will be:

Summary

In this article, you learned how to bind menu and sub menu dynamically in ASP.NET MVC from database using linq.

How To Create Menu And Submenu In Mvc 5

Source: https://www.c-sharpcorner.com/article/bind-menu-and-sub-menu-dynamically-in-mvc-from-database-using-linq/

Posted by: hoglundthatounhould.blogspot.com

0 Response to "How To Create Menu And Submenu In Mvc 5"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel