How to Create Dynamic Menu in Asp.Net Core MVC C#

In this article, we will learn How to Create a Dynamic Menu in Asp.Net Core MVC C#. In the previous article, we discussed https://labpys.com/how-to-generate-qr-code-using-asp-net-core-c/.

Dynamic Menu in Asp.Net Core MVC C#

Prerequisites

  • Download and install .Net Core 6.0 SDK from here
  • Download and Install Microsoft Visual Studio 2022 from here
  • Sql-Server

Create an ASP.NET Core MVC Project

Open visual studio, Go to File menu and click on New and select Project. Then new project window, select ASP.NET Core Web Application (Model-View-Controller) template.

Dynamic Menu in Asp.Net Core MVC C#

Enter  project name and click create.

Dynamic Menu in Asp.Net Core MVC C#

Install NuGet Packages

  • Microsoft Entity Framework Core Sql Server.
  • Microsoft Entity Framework Core Tools

Configure appsettings.json

There are two connection string one is SQL Server and another one is excel .

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "sqlconnection": "Server=(local)\\MSSQL;Database=InventoryDB;Trusted_Connection=True;MultipleActiveResultSets=true",   
    
  },
  "AllowedHosts": "*"
}

Create Model

Create Model class and DbContext Class.

//MenuMast.cs

using DocumentFormat.OpenXml.Presentation;
using System.ComponentModel.DataAnnotations;

namespace Asp.netcore_Tutorials.Models
{
    public class MenuMast
    {
        public MenuMast()
        {
            SubMenuMast = new HashSet<SubMenuMast>();
        }

        [Key]
        public int MenuCode { get; set; }

        [Required]
        [StringLength(250)]
        public string MenuName { get; set; }

        [StringLength(10)]
        public string DesignCodeTime { get; set; }

        public int? MenuSortOrder { get; set; }

        public virtual ICollection<SubMenuMast> SubMenuMast { get; set; }

    }
}

SubMenuMast.cs

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Asp.netcore_Tutorials.Models
{
    public class SubMenuMast
    {
        
        [Key]
        public int SubMenuCode { get; set; }

        public int ModuleCode { get; set; }
     
        [Required]
        [StringLength(150)]
        public string SubMenuName { get; set; }

        [StringLength(150)]
        public string TableName { get; set; }

        public bool HideFlag { get; set; }

        public int? SubMenuSortOrder { get; set; }

        public int MenuCode { get; set; }
        [ForeignKey(nameof(MenuCode))]
        public virtual MenuMast MenuMasts { get; set; } 
    }
}

MenuDbcontext.cs

using Microsoft.EntityFrameworkCore;

namespace Asp.netcore_Tutorials.Models
{
    public class MenuDbcontext : DbContext 
    {
        public MenuDbcontext(DbContextOptions<MenuDbcontext> option):base(option)
        {

        }

        public virtual DbSet<MenuMast> MenuMasts { get; set; }
        public virtual DbSet<SubMenuMast> SubMenuMasts { get; set; }
   
    }
}

Create Interface and Concrete Class

Interface IMenuNavigation.cs

using Asp.netcore_Tutorials.Models;

namespace Asp.netcore_Tutorials.Repository
{
    public interface IMenuNavigation
    {
        Task<IEnumerable<SubMenuMast>> MenuList();
        Task<IEnumerable<MenuMast>> MenuMastList();             
    }
}

Concrete Class MenuNavigation.cs

using Asp.netcore_Tutorials.Models;
using Microsoft.EntityFrameworkCore;
using System.Collections;

namespace Asp.netcore_Tutorials.Repository
{
    public class MenuNavigation : IMenuNavigation
    {
        private readonly MenuDbcontext _menuDbcontext;

        public MenuNavigation(MenuDbcontext menuDbcontext)
        {
            _menuDbcontext = menuDbcontext;
        }
        public async Task<IEnumerable<SubMenuMast>> MenuList()
        {
            return await _menuDbcontext.SubMenuMasts.Include(m=>m.MenuMasts).ToListAsync();
        }
        public async Task<IEnumerable<MenuMast>> MenuMastList()
        {
             return await _menuDbcontext.MenuMasts.Include(m=>m.SubMenuMast).ToListAsync();
        }
    }
}

Configure Program.cs

using Asp.netcore_Tutorials.Models;
using Asp.netcore_Tutorials.Repository;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Configuration;
using Microsoft.AspNetCore.Session;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

 
builder.Services.AddDbContext<MenuDbcontext>(conn => conn.UseSqlServer(builder.Configuration.GetConnectionString("sqlconnection")));
 
builder.Services.AddScoped<IMenuNavigation, MenuNavigation>();

builder.Services.AddSession();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.UseSession();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Migration

Add-Migration 'Initial-Create'
Update-Database

Create View Model

menuViewModel.cs

using Asp.netcore_Tutorials.Models;

namespace Asp.netcore_Tutorials.ViewModel
{
    public class menuViewModel
    {
      //  public  ICollection<SubMenuMast> menuListViewModel { get; set; }
        public IEnumerable<MenuMast> MenuList { get; set; }
    }
}

Create Controller

MenuController.cs

using Asp.netcore_Tutorials.Repository;
using Microsoft.AspNetCore.Mvc;
using Asp.netcore_Tutorials.ViewModel;
using Microsoft.AspNetCore.Mvc.Rendering;
using Asp.netcore_Tutorials.Models;

namespace Asp.netcore_Tutorials.Controllers
{
    public class MenuController : Controller
    {
        private readonly IMenuNavigation _menuList;

        public MenuController(IMenuNavigation menuList)
        {
            _menuList = menuList;
        }

        public IActionResult Index()
        {
            menuViewModel menuListViewModel = new menuViewModel();     
            menuListViewModel.MenuList =  _menuList.MenuMastList().Result.ToList();
            return View(menuListViewModel);
        }
    }
}

Customize View

index.cs

 
@model Asp.netcore_Tutorials.ViewModel.menuViewModel;
 
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <title></title>

        <!-- Bootstrap CSS CDN -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <!-- Our Custom CSS -->
      
        <!-- Scrollbar Custom CSS -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css">

         
       <link href="~/css/style.css" rel="stylesheet" />

    </head>
    <body>
        <div class="wrapper">
            <!-- Sidebar Holder -->
            <nav id="sidebar">
                <div class="sidebar-header">
                    <h3>Dynamic Menu</h3> 
                </div>

                <ul class="list-unstyled components">
                 @foreach (var menu in Model.MenuList)
                 {
                  <li class="active">
                        <a href="#@menu.MenuName" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">@menu.MenuName</a>
                    <ul class="collapse list-unstyled" id="@menu.MenuName">
                       @if (@menu.SubMenuMast.Count > 0)
                            {
                                @foreach (var item in menu.SubMenuMast)
                                {
                                    <li><a href="@item.SubMenuName">@item.SubMenuName</a></li>
                                }; 
                            };                     
                    
                    </ul>
                    </li>
                   };
                  </ul>              
            </nav>

            <!-- Page Content Holder -->
            <div id="content">

                <nav class="navbar navbar-default">
                    <div class="container-fluid">

                        <div class="navbar-header">
                            <button type="button" id="sidebarCollapse" class="btn btn-info navbar-btn">
                                <i class="glyphicon glyphicon-align-left"></i>
                                <span>Toggle Sidebar</span>
                            </button>
                        </div>

                        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                            <ul class="nav navbar-nav navbar-right">
                                <li><a href="#">Page</a></li>
                            </ul>
                        </div>
                    </div>
                </nav>

            
            </div>
        </div>

         <!-- jQuery CDN -->
    <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
    <!-- Bootstrap Js CDN -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <!-- jQuery Custom Scroller CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>
 
 
    <script type="text/javascript">
        $(document).ready(function () {

            $('#sidebarCollapse').on('click', function () {
                $('#sidebar').toggleClass('active');
            });

        });
    </script>
    </body>
</html>

 
0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
fatma
fatma
1 year ago

how to view menu in layout? please

Vijayachandran Uvarajan
Vijayachandran Uvarajan
1 year ago

Can I get the source Code?