Loading, please wait...

A to Z Full Forms and Acronyms

How to create multi-level menus dynamically in Asp.net MVC

I will explain How to create multi-level menus dynamically in Asp.net MVC. This is code snippet how to develop multi level menu with UL and LI structure in MVC structure

Are you preparing for the next job interviews in Microsoft ASP.NET MVC? If yes, trust me this post will help you also we'll suggest you check out a big collection for Programming Full Forms that may help you in your interview:

List of Programming Full Forms 

Introduction:

Today in this article, I will How to create multi-level menus dynamically in Asp.net MVC.

I have created a project in which rendered a menu dynamically from the database using Ado.net. I have to add a Model into my Models Folder and in this model, I have my menu tables

A menu plays a significant role in lending an amazing UX by making an application easily navigable. It can be used to make accessibility to a particular section a breeze. Here is a comprehensive guide that offers a complete tutorial for creating a user-friendly multi-level dynamic menu via ASP.NET MVC.

Follow these steps in order to implement “Multi-Level menus dynamically in Asp.net MVC”

Step1: Create tables in a database.

In this example, I have created the following three tables for binding 3 level dynamic menus.

Create tbl_category table for first level menus.

CREATE TABLE [dbo].[tbl_category] (

    [Cat_id]        INT            IDENTITY (1, 1) NOT NULL,

    [Category_Name] NVARCHAR (MAX) NULL,

    CONSTRAINT [PK_tbl_category] PRIMARY KEY CLUSTERED ([Cat_id] ASC)

);

 The design of the table look like this as follows:

 

Now create tbl_Subcategory table for bind second level menus.

CREATE TABLE [dbo].[tbl_Subcategory] (

    [Subcat_id]   INT            IDENTITY (1, 1) NOT NULL,

    [Cat_id]      INT            NULL,

    [Subcat_name] NVARCHAR (MAX) NULL,

    CONSTRAINT [PK_tbl_Subcategory] PRIMARY KEY CLUSTERED ([Subcat_id] ASC)

);

The design of the table look like this as follows:

 

In last we create tbl_subtosucategory for bind third level menus

CREATE TABLE [dbo].[tbl_subtosucategory] (

    [SubtosubCat_id]   INT           NULL,

    [Subcat_id]        INT           NULL,

    [SubtosubCat_Name] NVARCHAR (50) NULL

);

The design of the table look like this as follows:

 

Step2: Create New Project.

 Go to File > New > Project > Web > Asp.net MVC web project > Enter Application Name > Select your project location > click to OK button > It will show new dialog window for select template > here we will select MVC project > then click to ok

Step3: Add Connection string in web.config file

Here I have added connection string in the web.config file under the Configuration section as follows:

<connectionStrings>

    <add name="con" connectionString="Data Source=.;Initial Catalog=Menutest;Integrated Security=True " providerName="System.Data.SqlClient"/>

  </connectionStrings>

Step5: Create a Model for menus.

I have added these three classes for multilevel menus. Fallowing class for first level menus.

public class category
    {
        public int Catid { get; set; }
        public string category_name { get; set; }
    }

Now I have added a class for second-level menus:

public class Subcategory
    {
        public int Subcat_id { get; set; }
        public int Cat_id { get; set; }
        public string Subcat_name { get; set; }
    }

I last we need to add class for third level menus.

public class subtosubcategory
    {
        public int Subtosubcat_id { get; set; }
        public int Subcat_id { get; set; }
        public string Subtosubcat_Name { get; set; }
    }

Step5: Create a Database Access layer.

Go to Solutions Explorer > right click on project solution> Add New Folder > Enter Folder name (Here I rename it as ‘database_access_layer’) > right click on folder > Add new class.

 

Now add the following method into Database access class that access record on the basis of parameters.

Firstly we need to add connection string in db class file as follows:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);

Now we need to add fallowing three methods for binding three level menus

//Get Category
        public DataSet get_category()
        {
            SqlCommand com = new SqlCommand("Select * from tbl_category", con);
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }
        //Get Subcategory()
        public  DataSet get_Subcategory(int catid)
        {
            SqlCommand com = new SqlCommand("Select * from tbl_Subcategory where Cat_id=@catid", con);
            com.Parameters.AddWithValue("@catid", catid);
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }
        //Get Subtosubcategory
        public DataSet get_SubtoSubcategory(int subcatid)
        {
            SqlCommand com = new SqlCommand("Select * from tbl_subtosucategory where Subcat_id=@subcatid", con);
            com.Parameters.AddWithValue("@subcatid", subcatid);
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }

The entire DB class file will be fallows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace Multilevel_Menu.database_Access_layer
{
    public class db
    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
        //Get Category
        public DataSet get_category()
        {
            SqlCommand com = new SqlCommand("Select * from tbl_category", con);
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }

        //Get Subcategory()
        public  DataSet get_Subcategory(int catid)
        {
            SqlCommand com = new SqlCommand("Select * from tbl_Subcategory where Cat_id=@catid", con);
            com.Parameters.AddWithValue("@catid", catid);
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }

        //Get Subtosubcategory
        public DataSet get_SubtoSubcategory(int subcatid)
        {
            SqlCommand com = new SqlCommand("Select * from tbl_subtosucategory where Subcat_id=@subcatid", con);
            com.Parameters.AddWithValue("@subcatid", subcatid);
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }
    }
}

And also you will see the methods is taking an input parameter cat_id and subcatid (this is the id of the first level menu and second level menu respectively)

Step6: Create a Controller

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

Here I have created a controller "HomeController.

Step7: Add View in HomeController

After adding the controller to the application I am just adding a new action result and naming it Index and also we need to call DB class in HomeController.

In Index action method I have called get_category from DB class for the first level menu

Database_Access_Layer.db dblayer = new Database_Access_Layer.db();

public ActionResult Index()
        {
            DataSet ds = dblayer.get_category();
            ViewBag.category = ds.Tables[0];
            return View();
        }

Step7: Add methods for Binding and populate second and third-level menus

Now we will add the following functions in HomeController to populate second and third-level menus.

 Add below methods for the populate second-level menu:

public void get_Submenu(int catid)
        {
            DataSet ds = dblayer.get_Subcategory(catid);
            List<Subcategory> submenulist = new List<Subcategory>();
            foreach (DataRow  dr in ds.Tables[0].Rows)
            {
            submenulist.Add(new Subcategory{
            Subcat_id=Convert.ToInt32(dr["Subcat_id"]),
            Subcat_name=dr["Subcat_name"].ToString()
            });
            }
            Session["submenu"] = submenulist;
        }

In the above methods, I am calling get_Subcategory methods from the DB class and storing the list in Session for the passing list to the view. It’s also contain input parameter catid that is value of first level menu

Now we will be adding a method for third level menu:

public void get_Subtosubmenu(int Subcat_id)
        {
            DataSet ds = dblayer.get_SubtoSubcategory(Subcat_id);
            List<subtosubcategory> subtosubmenulist = new List<subtosubcategory>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                subtosubmenulist.Add(new subtosubcategory
                {
                    Subtosubcat_id = Convert.ToInt32(dr["Subcat_id"]),
                    Subtosubcat_Name = dr["SubtosubCat_Name"].ToString()
                });
            }
            Session["subtosubmenu"] = subtosubmenulist;
        }

In the above method, I have taken Subcat_id  as a parameter that is the value of second-level menu item as store list in Session for access to view.

Now entire HomeController class file will be as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using Multilevel_Menu.Models;
namespace Multilevel_Menu.Controllers
{
    public class HomeController : Controller
    {
        // GET: /Home/
        database_Access_layer.db dblayer = new database_Access_layer.db();
        public ActionResult Index()
        {
            DataSet ds = dblayer.get_category();
            ViewBag.category = ds.Tables[0];
            return View();
        }
        // Get submenu
        public void get_Submenu(int catid)
        {
            DataSet ds = dblayer.get_Subcategory(catid);
            List<Subcategory> submenulist = new List<Subcategory>();
            foreach (DataRow  dr in ds.Tables[0].Rows)
            {
            submenulist.Add(new Subcategory{
            Subcat_id=Convert.ToInt32(dr["Subcat_id"]),
            Subcat_name=dr["Subcat_name"].ToString()
            });
            }
            Session["submenu"] = submenulist;
        }

        // Get Subtosubmenu
        public void get_Subtosubmenu(int Subcat_id)
        {
            DataSet ds = dblayer.get_SubtoSubcategory(Subcat_id);
            List<subtosubcategory> subtosubmenulist = new List<subtosubcategory>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                subtosubmenulist.Add(new subtosubcategory
                {
                    Subtosubcat_id = Convert.ToInt32(dr["Subcat_id"]),
                   Subtosubcat_Name = dr["SubtosubCat_Name"].ToString()
                });
            }
            Session["subtosubmenu"] = subtosubmenulist;
        }
    }
}

Step8: Add View for the Index action

Right Click on Action Method (here right click on Index action) > Add View > Enter View Name > Select "Empty" under Template dropdown > Check use a layout page > Add.

Further, we need to add the following code under Index.cshtml where you want to show menus.

<ul>
                @{
                    foreach (System.Data.DataRow dr in ViewBag.category.Rows)
                    {
                         <li>
                    <a href='#'>@dr["Category_Name"]</a>
                       @{  
                        ((Multilevel_Menu.Controllers.HomeController)this.ViewContext.Controller).get_Submenu(Convert.ToInt32(dr["Cat_id"]));
                       }
                             <ul>
                                 @{
                        foreach (Multilevel_Menu.Models.Subcategory subitem in Session["submenu"] as List<Multilevel_Menu.Models.Subcategory>)
                        {
                         <li>
                             <a href='#'>@subitem.Subcat_name</a>
                             @{
                       ((Multilevel_Menu.Controllers.HomeController)this.ViewContext.Controller).get_Subtosubmenu(Convert.ToInt32(subitem.Subcat_id));
                             }
                             <ul>
                                 @{
                            foreach (Multilevel_Menu.Models.subtosubcategory subtosubitem in Session["subtosubmenu"] as List<Multilevel_Menu.Models.subtosubcategory>)
                            {
                             <li><a href='#'>@subtosubitem.Subtosubcat_Name</a></li>
                            }
                                 }
                             </ul>
                         </li>
                        }
                                 }
                             </ul> 
                </li> 
                }
                } 
            </ul>

For complete design and look we need to add some CSS and JQuery files.

For CSS and JQuery files click here.

Now entire Index.cshtml file will be as follows:

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>CSS3 Responsive Menu Dropdown + Submenu width Logo</title>
    <link rel="stylesheet" href="~/css/style.css">
</head>

<body>
    <header>
        <nav id='cssmenu'>
            <div class="logo"><a href="index.html">Responsive </a></div>
            <div id="head-mobile"></div>
            <div class="button"></div>
            <ul>
                @{
                    foreach (System.Data.DataRow dr in ViewBag.category.Rows)
                    {
                         <li>
                    <a href='#'>@dr["Category_Name"]</a>
                     @{  
                        ((Multilevel_Menu.Controllers.HomeController)this.ViewContext.Controller).get_Submenu(Convert.ToInt32(dr["Cat_id"]));
                       }
                             <ul>
                                 @{
                        foreach (Multilevel_Menu.Models.Subcategory subitem in Session["submenu"] as List<Multilevel_Menu.Models.Subcategory>)
                        {
                         <li>
                             <a href='#'>@subitem.Subcat_name</a>
                             @{
                        ((Multilevel_Menu.Controllers.HomeController)this.ViewContext.Controller).get_Subtosubmenu(Convert.ToInt32(subitem.Subcat_id));
                             }
                             <ul>
                                 @{
                            foreach (Multilevel_Menu.Models.subtosubcategory subtosubitem in Session["subtosubmenu"] as List<Multilevel_Menu.Models.subtosubcategory>)
                            {
                             <li><a href='#'>@subtosubitem.Subtosubcat_Name</a></li>
                            } }
                             </ul>
                         </li>
}  }
                            </ul> 
 </li>
 } }
</ul>
 </nav>
</header>
<section style='padding-top:20px;font:bold  44px arial;color:#68D800;'>
        Responsive CSS3 Menu <br />Dropdown + Submenus <br />
        Width Toggle Animation
    </section>
    <script src="~/js/jquery-1.10.2.min.js"></script>
   <script src="~/js/index.js"></script>
</body>
</html>

Step 10: Run Application.

We have done all steps, now it’s time to run the application.

I hope this helps you to do the same in your application.

More Interview Questions and Answers:

A to Z Full Forms and Acronyms