JQuery UI Dynamic Menu

Here are the steps,
 
Step 1: Open SQL Server Management Studio and create a database named DemoDB and use the following script to create the table, insert sample data and also to create Stored procedure which will be used in Visual Studio to retrieve data.
  1. CREATE TABLE [dbo].[jquerymenu] (  
  2.     [ID]       INT           IDENTITY (1, 1) NOT NULL,  
  3.     [Text]     NVARCHAR (50) NULL,  
  4.     [parentId] INT           NULL,  
  5.     [isActive] BIT           NULL  
  6. );  
  7.    
  8. SET IDENTITY_INSERT [dbo].[jquerymenu] ON  
  9. INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (1, N'USA'NULL, 1)  
  10. INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (2, N'India'NULL, 1)  
  11. INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (3, N'UK'NULL, 1)  
  12. INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (4, N'Australia'NULL, 1)  
  13. INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (5, N'Virginia', 1, 1)  
  14. INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (6, N'Maryland', 1, 1)  
  15. INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (7, N'AP', 2, 1)  
  16. INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (8, N'MP', 2, 1)  
  17. INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (9, N'Karnataka', 2, 1)  
  18. INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (10, N'Bangalore', 9, 1)  
  19. INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (11, N'Mangalore', 9, 1)  
  20. INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (12, N'Mysore', 9, 0)  
  21. SET IDENTITY_INSERT [dbo].[jquerymenu] OFF  
  22.    
  23. Create Proc spGetMenuData  
  24. as  
  25. Begin  
  26.     Select * from jquerymenu  
  27. End  
Step 2: Open Visual Studio and create an empty ASP.NET Web application. Then folow the below mentioned steps.

Add Class file

 
Add Webform

 
Add Handler

 
Step 3: Add a Connection String for connection to database in Web.Config file. 
  1. <connectionStrings>  
  2.     <add name="DBCS" connectionString="server=.;database=DemoDB;integrated security=SSPI" providerName="System.Data.SqlClient"/>  
  3.   </connectionStrings>  
Step 4: Create Auto-populated properties in the class file created in Step 2.
  1. using System.Collections.Generic;  
  2.    
  3. namespace jQueryUIMenu  
  4. {  
  5.     public class Menu  
  6.     {  
  7.         public int ID { getset; }  
  8.         public string Text { getset; }  
  9.         public int? parentId { getset; }  
  10.         public bool isActive { getset; }  
  11.         public List<Menu> List { getset; }  
  12.     }  
  13. }  
Step 5: Add the following code to the Generic Handler which will retrieve data from the database.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Data;  
  6. using System.Data.SqlClient;  
  7. using System.Web.Script.Serialization;  
  8. using System.Configuration;  
  9.    
  10. namespace jQueryUIMenu  
  11. {  
  12.     public class MenuHandler : IHttpHandler  
  13.     {  
  14.         public void ProcessRequest(HttpContext context)  
  15.         {  
  16.             var cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  17.             var list = new List<Menu>();  
  18.    
  19.             using (var con = new SqlConnection(cs))  
  20.             {  
  21.                 var cmd = new SqlCommand("spGetMenuData", con) { CommandType = CommandType.StoredProcedure };  
  22.                 con.Open();  
  23.                 var dr = cmd.ExecuteReader();  
  24.                 while (dr.Read())  
  25.                 {  
  26.                     var menu = new Menu  
  27.                     {  
  28.                         ID = Convert.ToInt32(dr["ID"]),  
  29.                         Text = dr["Text"].ToString(),  
  30.                         parentId = dr["parentId"] != DBNull.Value ? Convert.ToInt32(dr["parentId"]) : (int?)null,  
  31.                         isActive = Convert.ToBoolean(dr["isActive"])  
  32.                     };  
  33.                     list.Add(menu);  
  34.                 }  
  35.             }  
  36.             var mainList = GetMenuTree(list, null);  
  37.    
  38.             var js = new JavaScriptSerializer();  
  39.             context.Response.Write(js.Serialize(mainList));  
  40.    
  41.         }  
  42.    
  43.         private List<Menu> GetMenuTree(List<Menu> list, int? parent)  
  44.         {  
  45.             return list.Where(x => x.parentId == parent).Select(x => new Menu  
  46.             {  
  47.                 ID = x.ID,  
  48.                 Text = x.Text,  
  49.                 parentId = x.parentId,  
  50.                 isActive = x.isActive,  
  51.                 List = GetMenuTree(list, x.ID)  
  52.             }).ToList();  
  53.         }  
  54.    
  55.         public bool IsReusable => false;  
  56.     }  
  57. }  
Step 6: Add the following code to the Body Tag of Webform1.aspx.
  1. <body>  
  2.     <form id="form1" runat="server">  
  3.         <div style="width: 150px">  
  4.             <ul id="menu"></ul>  
  5.         </div>  
  6.     </form>  
  7. </body>  
Step 7: Add jQuery UI core files as shown below.

 
Step 8: Add the following jQuery code to the Head Tag of Webform1.aspx.
  1. <head runat="server">  
  2.     <title>Dynamic Menu</title>  
  3.     <script src="Scripts/jquery-1.6.4-vsdoc.js"></script>  
  4.     <script src="Scripts/jquery-1.6.4.js"></script>  
  5.     <script src="Scripts/jquery-ui-1.11.4.js"></script>  
  6.     <link href="Content/themes/base/all.css" rel="stylesheet" />  
  7.     <script type="text/javascript">  
  8.         $(document).ready(function () {  
  9.             $.ajax({  
  10.                 url: 'MenuHandler.ashx',  
  11.                 method: 'get',  
  12.                 dataType: 'json',  
  13.                 success: function (data) {  
  14.                     buildMenu($('#menu'), data);  
  15.                     $('#menu').menu();  
  16.                 }  
  17.             });  
  18.    
  19.             function buildMenu(parent, items) {  
  20.                 $.each(items, function () {  
  21.                     var li = $('<li>' + this.Text + '</li>');  
  22.                     if (!this.isActive) {  
  23.                         li.addClass("ui-state-disabled");  
  24.                     }  
  25.                     li.appendTo(parent);  
  26.                     if (this.List && this.List.length > 0) {  
  27.                         var ul = $('<ul></ul>');  
  28.                         ul.appendTo(li);  
  29.                         buildMenu(ul, this.List);  
  30.                     }  
  31.                 });  
  32.             }  
  33.         });  
  34.     </script>  
  35. </head>  
Step 9: Press Ctrl + F5 together to View the result in browser. You will see a menu having values populated from the database.

Hope you enjoyed the example. Please share it if you think that it can be useful to others. Also comment in case of any query.

Up Next
    Ebook Download
    View all
    Learn
    View all