Tuesday, December 15, 2015

Create Dynamic Menu in MVC from DataBase

In this article I am going to explain how to create dynamic menu in MVC

Step 1

Go to File->New->Project



After clicking on Project a new window will be open. In it select "ASP.NET MVC 4 Web Application" and rename Solution Name to "DynamicMenuInMVC" and click on "OK" Button.





After clicking on "ok" button a new window will be open, in it select "Basic" template and click on ok
Step 2
At the Solution explorer right click on Model folder  Add->Class


A new window will be open, select a class rename it to "MenuModel.cs"




Now Code in "MenuModel.cs"


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace DynamicMenuInMVC.Models
{
   
    public class MenuModel
    {
        public List<ParentMenu> ParentMenuModel { get; set; }
        public List<ChildMenu> ChildMenuModel { get; set; }
    }
    public class ChildMenu
    {
        public int NodeId { get; set; }
        public int ParentId { get; set; }
        public string ChildName { get; set; }
        public string ChildUrl { get; set; }
        public string ChildController { get; set; }
    }
    public class ParentMenu
    {
        public int Id { get; set; }
        public string ParentName { get; set; }
        public string ParentUrl { get; set; }
        public string ParentController { get; set; }
    }
    public class GetMenuItem
    {
        public DataSet GetMeuItems()
        {
            SqlDataAdapter _da = new SqlDataAdapter("Usp_GetMenuItem", ConfigurationManager.ConnectionStrings["Constr"].ToString());
            _da.SelectCommand.CommandType = CommandType.StoredProcedure;
            DataSet ds = new DataSet();
            _da.Fill(ds);
            return ds;
        }
    }
}  

Step 3

Now I edited some content in "_Layout.cshtml"


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <ul id="menu">
        @{ Html.RenderAction("Index", "Home"); }
    </ul>
    <section id="main">
    @RenderBody()
    @Scripts.Render("~/bundles/jquery")
    @RenderSection("scripts", required: false)
</body>
</html>
Step 4

After Completing step 3 , at the solution explorer add a controller in controller folder  name "HomeController"




Now Click on "Add" button

HomeController.cs code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DynamicMenuInMVC.Models;
using System.Data;
using System.Data.SqlClient;
namespace DynamicMenuInMVC.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            MenuModel objmenumodel = new MenuModel();
            objmenumodel.ChildMenuModel = new List<ChildMenu>();
            objmenumodel.ChildMenuModel = GetChildList();
            objmenumodel.ParentMenuModel = new List<ParentMenu>();
            objmenumodel.ParentMenuModel = ParentMenuList();
            return View(objmenumodel);
        }
        public List<ChildMenu> GetChildList()
        {
            List<ChildMenu> objchildmenu = new List<ChildMenu>();
            GetMenuItem obj = new GetMenuItem();
            DataSet ds = obj.GetMeuItems();
            if (ds.Tables[1] != null)
            {
                if (ds.Tables[1].Rows.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[1].Rows.Count; i++)
                    {
                        objchildmenu.Add(new ChildMenu { NodeId = (int)(int)ds.Tables[1].Rows[i]["NodeId"], ParentId = (int)ds.Tables[1].Rows[i]["Underparent"], ChildName = (string)ds.Tables[1].Rows[i]["ModeName"], ChildUrl = (string)ds.Tables[1].Rows[i]["Url"], ChildController = (string)ds.Tables[1].Rows[i]["Controller"] });
                    }
                }
            }
            return objchildmenu;
        }
      
        public List<ParentMenu> ParentMenuList()
        {
            List<ParentMenu> objparentmenu = new List<ParentMenu>();
            GetMenuItem obj = new GetMenuItem();
            DataSet ds = obj.GetMeuItems();
            if (ds.Tables[0] != null)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    for(int i=0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        objparentmenu.Add(new ParentMenu { Id = (int)ds.Tables[0].Rows[i]["NodeId"], ParentName = (string)ds.Tables[0].Rows[i]["ModeName"], ParentUrl = (string)ds.Tables[0].Rows[i]["Url"], ParentController = (string)ds.Tables[0].Rows[i]["Controller"] });
                    }
                }
            }
            return objparentmenu;
        }
        public ActionResult Menu3()//here for menu 3 click
        {
            return View();
        }
    }
}

Step 5

Now right click at ActionResult index method and add a view



a new new window will be open now click on "Add" button.




Code of "Index.cshtml"

@model DynamicMenuInMVC.Models.MenuModel
@{
    ViewBag.Title = "Index";
    Layout = null;
}
<style type="text/css">
nav {
       margin: 10px auto;
       text-align: center;
}
nav ul ul {
       display: none;
}
       nav ul li:hover > ul {
              display: block;
       }
nav ul {
       background: #efefef;
       background: linear-gradient(top, #efefef 0%, #bbbbbb 100%)
       background: -moz-linear-gradient(top, #efefef 0%, #bbbbbb 100%);
       background: -webkit-linear-gradient(top, #efefef 0%,#bbbbbb 100%);
       box-shadow: 0px 0px 9px rgba(0,0,0,0.15);
       padding: 0 20px;
       border-radius: 10px
       list-style: none;
       position: relative;
       display: inline-table;
}
       nav ul:after {
              content: ""; clear: both; display: block;
       }
       nav ul li {
              float: left;
       }
              nav ul li:hover {
                     background: #4b545f;
                     background: linear-gradient(top, #4f5964 0%, #5f6975 40%);
                     background: -moz-linear-gradient(top, #4f5964 0%, #5f6975 40%);
                     background: -webkit-linear-gradient(top, #4f5964 0%,#5f6975 40%);
              }
                     nav ul li:hover a {
                           color: #fff;
                     }
             
              nav ul li a {
                     display: block; padding: 10px 10px;
                     color: #757575; text-decoration: none;
              }
                    
             
       nav ul ul {
              background: #5f6975; border-radius: 0px; padding: 0;
              position: absolute; top: 100%;
              z-index:2000;
       }
              nav ul ul li {
                     float: none;
                     border-top: 1px solid #6b727c;
                     border-bottom: 1px solid #575f6a; position: relative;
              }
                     nav ul ul li a {
                           padding: 15px 40px;
                           color: #fff;
                           width:120px;
                     }     
                           nav ul ul li a:hover {
                                  background: #4b545f;
                           }
             
       nav ul ul ul {
              position: absolute; left: 100%; top:0;
       }
             
    </style>
@using (Html.BeginForm("Index", "Home"))
{
<nav>
        <ul>
            @{
    foreach (var iteparent in Model.ParentMenuModel)
    {
        var childitem = Model.ChildMenuModel.Where(m => m.ParentId == iteparent.Id);
        if (childitem.Count() == 0)
        {          
           
            <li> <a href="@Url.Action(@iteparent.ParentUrl, @iteparent.ParentController)" class="elements"><span>@iteparent.ParentName</span></a></li>          
               
        }
        else
        {
              
                <li> <a href="@Url.Action(@iteparent.ParentUrl,@iteparent.ParentController)" class="elements"><span>@iteparent.ParentName</span></a>
                    @if (childitem.Count() > 0)
                    {              
                        <ul>
                            @foreach (var itemchild in childitem)
                            {
                                    <li> <a href="@Url.Action( @itemchild.ChildUrl,@itemchild.ChildController)" class="elements"><span>@itemchild.ChildName</span></a>
                                  @foreach (var subChildMenu in Model.ChildMenuModel)
                                  {
                                      if (subChildMenu.ParentId == itemchild.NodeId)
                                      {
                                          <ul>
                                          @foreach (var subChildMenu1 in Model.ChildMenuModel)
                                          {
                                              if (subChildMenu1.ParentId == itemchild.NodeId)
                                              {
                                                 <li> <a href="@Url.Action(@subChildMenu1.ChildController,@subChildMenu1.ChildUrl)" class="elements"><span>@subChildMenu1.ChildName</span></a></li>
                                              }
                                          }
                                          </ul>
                                      }
                                  }
                              
                                </li>
                            }
                        </ul>
                    }</li>
        }
    }
               
            }
        </ul>
    </nav>
}


for database Script

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Menu](
                [NodeId] [int] IDENTITY(1,1) NOT NULL,
                [ModeName] [nvarchar](50) NOT NULL,
                [Underparent] [int] NOT NULL,
                [ViewName] [nvarchar](50) NULL,
                [Controller] [nvarchar](50) NULL,
PRIMARY KEY CLUSTERED
(
                [NodeId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[Menu] ON
INSERT [dbo].[Menu] ([NodeId], [ModeName], [Underparent], [ViewName], [Controller]) VALUES (1, N'Menu1', 0, N'Index', N'Home')
INSERT [dbo].[Menu] ([NodeId], [ModeName], [Underparent], [ViewName], [Controller]) VALUES (2, N'Menu2', 0, N'Index', N'Home')
INSERT [dbo].[Menu] ([NodeId], [ModeName], [Underparent], [ViewName], [Controller]) VALUES (3, N'Menu3', 1, N'Menu3', N'Home')
SET IDENTITY_INSERT [dbo].[Menu] OFF
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Usp_GetMenuItem]
WITH EXECUTE AS CALLER
AS
begin
  select  NodeId,ModeName, ViewName as Url,Controller from Menu  where Underparent=0
  select  NodeId,Underparent,ModeName,ViewName as Url,Controller from Menu  where Underparent!=0
end


Run your application output is



1 comment: