.

Monday, 28 July 2014

Dynamic Css Menu Creation in Asp.Net Using C#.Net

7/28/2014 - By Pranav Singh 8

Dynamic menu creation is one of the most important parts if a website development. So today I will show you how you can create dynamic css menu using in asp.net using CSS/CSS3.  This will cover label 2 menu.


First we will search for the menu which we want to implement dynamically. Now download the menu and incorporate the static menu in your application. Now follow the below tutorial to create the dynamic menu.

After this we will create table in which we will add the menu item detail. In this article I have used two table one for parent and other for child table. In this child table contains the reference of parent table.
Parent Table:


Child Table:


So for this article first we will create a new asp.net application and add the menu detail like css .

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RoleBasedMenu.aspx.cs"
    Inherits="ProjectDemo_Asp.et.RoleBasedMenu" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Dynamic Css Menu Creation in Asp.Net Using C#.Net</title>
    <style type="text/css">
        ul
        {
            list-stylenone;
            padding0px;
            margin0px;
        }
        ul li
        {
            displayblock;
            positionrelative;
            floatleft;
            border1px solid #000;
        }
        li ul
        {
            displaynone;
        }
        ul li a
        {
            displayblock;
            backgroundgreen;
            padding5px 10px 5px 10px;
            text-decorationnone;
            white-spacenowrap;
            color#fff;
        }
        ul li a:hover
        {
            backgroundblack;
        }
        li:hover ul
        {
            displayblock;
            positionabsolute;
        }
        li:hover li
        {
            floatnone;
        }
        li:hover a
        {
            backgroundgreen;
        }
        li:hover li a:hover
        {
            background#000;
        }
        #drop-nav li ul li
        {
            border-top0px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div runat="server" id="divmenu">
       
    </div>
    </form>
</body>
</html>

Now just check the div control I have added runat="server". This I have to bind the record which I will generate from code end.

Now check the code used for making the dynamic menu. 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using System.Data.SqlClient;

namespace ProjectDemo_Asp.et
{
    public partial class RoleBasedMenu : System.Web.UI.Page
    {
        public string connectionstring = "<----your connection="" string----="">";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetMenuData();
            }
        }
        /// 
        /// This method will return data for menu creation
        /// 
        /// 
        public void GetMenuData()
        {
            StringBuilder objstr = new StringBuilder();
            List<MenuParant> objpmenu = new List<MenuParant>();
            List<MenuChild> objcmenu = new List<MenuChild>();
            objpmenu = GetParantMenu();
            objcmenu = GetChildMenu();
            objstr.Append("< ul id=\"drop-nav\">");
            foreach (MenuParant _pitem in objpmenu)
            {
                objstr.Append("< li>< a href='" + _pitem.Url + "'>" + _pitem.MenuName + "< /a>");
                var childitem = objcmenu.Where(m => m.PairantId == _pitem.Id).ToList();
                if (childitem.Count > 0)
                {
                    objstr.Append("< ul>");
                    foreach (var _citem in childitem)
                    {
                        objstr.Append("< li>< a href='" + _citem.ChildUrl + "'>" + _citem.ChildName + "< /a></ li>");
                    }
                    objstr.Append("< /ul>");
                }
                objstr.Append("< /li>");
            }
            objstr.Append("< /ul>");
            divmenu.InnerHtml = objstr.ToString();
        }
        /// 
        /// Get Data from parant table
        /// 

        /// 
        public List<MenuParant> GetParantMenu()
        {
            List<MenuParant> objmenu = new List<MenuParant>();
            DataTable _objdt = new DataTable();
            string querystring = "select * from Menu;";
            SqlConnection _objcon = new SqlConnection(connectionstring);
            SqlDataAdapter _objda = new SqlDataAdapter(querystring, _objcon);
            _objcon.Open();
            _objda.Fill(_objdt);
            if (_objdt.Rows.Count > 0)
            {
                for (int i = 0; i < _objdt.Rows.Count; i++)
                {
                    objmenu.Add(new MenuParant { Id = (int)_objdt.Rows[i]["Id"], MenuName = _objdt.Rows[i]["ParentMenu"].ToString(), Url = _objdt.Rows[i]["ParentUrl"].ToString() });
                }
            }
            return objmenu;
        }
        /// 
        /// Get data from child dable
        /// 

        /// 
        public List<MenuChild> GetChildMenu()
        {
            List<MenuChild> objmenu = new List<MenuChild>();
            DataTable _objdt = new DataTable();
            string querystring = "select * from ChildMenu;";
            SqlConnection _objcon = new SqlConnection(connectionstring);
            SqlDataAdapter _objda = new SqlDataAdapter(querystring, _objcon);
            _objcon.Open();
            _objda.Fill(_objdt);
            if (_objdt.Rows.Count > 0)
            {
                for (int i = 0; i < _objdt.Rows.Count; i++)
                {
                    objmenu.Add(new MenuChild { PairantId = (int)_objdt.Rows[i]["ParentId"], ChildName = _objdt.Rows[i]["ChildMenu"].ToString(), ChildUrl = _objdt.Rows[i]["ChildUrl"].ToString() });
                }
            }
            return objmenu;
        }
    }

    /*Menu Class*/
    public class MenuParant
    {
        public int Id { getset; }
        public string MenuName { getset; }
        public string Url { getset; }
    }
    public class MenuChild
    {
        public int PairantId { getset; }
        public string ChildName { getset; }
        public string ChildUrl { getset; }
    }


}

       
Now check the above code I have used two function to retrieve the data from the tables. After fetching data from data base I have created a common function where I am using both the record collection.

Now just check the GetMenuData() function in this I have prepared the string of menu and bind the detail to the div control as html string.

Now we have done just call this function on page load and run the page to check the output.


DOWNLOAD

About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

8 comments:

  1. Working great! Thanks!

    ReplyDelete
  2. can u show how to do with 3 level menu.. please help...

    ReplyDelete
  3. can u show how to do with 3 level menu.. please help

    ReplyDelete
  4. it doesn't work for me. no colour or menu appear..why?

    ReplyDelete
  5. it preview as below...no menu, no colour..please help

    < ul id="drop-nav">< li>< a href=''>Publication Activities< /a>< ul>< li>< a href='/Publication/ListViewArticleJournal.aspx'>Article in Journal< /a>< li>< a href='/Publication/ListViewArticleProceeding.aspx'>Article In Proceeding< /a>< li>< a href='/Publication/ListViewBook.aspx'>Book

    ReplyDelete
    Replies
    1. Hi please download the code and then try it.
      please check there is gap between < ul id="drop-nav"> for displaying the code. without this gap it will display dot.

      Delete

Please let me know your view

Free Ebooks

Tips and Tricks

About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

Please contact Us

Email Id
: contact@aspdotnet-pools.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.
© 2014
back to top