Generate Dynamic Menu in ASP.NET C#
Menu is an important part of any project or application. It is used for navigation. Any project may have different modules and different user may access different modules. If we want to develop a system where we can assign which user will access which menu and it will be stored in a database, ASP.NET can help us. When a user log on to application, system will dynamically generate menu according to his/her permitted area. For this we need to generate menu dynamically. Static menu is not an ideal solution for this situation. ASP.NET can help us to do this. This article describes how to generate a menu dynamically in ASP.NET, dynamic menu in ASP.NET C#. Summary of the article:
- Table Creation
- Project Creation
- Adding a Connection String
- Implement Different Methods
- Generate the Dynamic Menu
- Output
Table Creation
At first we need to crate a table in our database. We cab use the following SQL scripts. This will create “Menus” table with some sample data.
At first we need to crate a table in our database. We cab use the following SQL scripts. This will create “Menus” table with some sample data.
CREATE TABLE [dbo].[Menus]( [MenuID] [bigint] NOT NULL, [ParentID] [bigint] NULL, [Name] [nvarchar](50) NULL, [URL] [nvarchar](50) NULL, CONSTRAINT[PK_Menus] PRIMARY KEY CLUSTERED ( [MenuID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] INSERT [dbo].[Menus]([MenuID], [ParentID], [Name], [URL]) VALUES (1, 0, 'Main Menu1', 'Main Menu1') INSERT [dbo].[Menus]([MenuID], [ParentID], [Name], [URL]) VALUES (2, 0, 'Main Menu2', 'Main Menu2') INSERT [dbo].[Menus]([MenuID], [ParentID], [Name], [URL]) VALUES (3, 0, 'Main Menu3', 'Main Menu3') INSERT [dbo].[Menus]([MenuID], [ParentID], [Name], [URL]) VALUES (4, 1, 'Sub Menu 1.1', 'Sub Menu 1.1') INSERT [dbo].[Menus]([MenuID], [ParentID], [Name], [URL]) VALUES (5, 1, 'Sub Menu 1.2', 'Sub Menu 1.2') INSERT [dbo].[Menus]([MenuID], [ParentID], [Name], [URL]) VALUES (6, 2, 'Sub Menu 2.1', 'Sub Menu 2.1') INSERT [dbo].[Menus]([MenuID], [ParentID], [Name], [URL]) VALUES (7, 2, 'Sub Menu 2.2', 'Sub Menu 2.2') INSERT [dbo].[Menus]([MenuID], [ParentID], [Name], [URL]) VALUES (8, 3, 'Sub Menu 3.1', 'Sub Menu 3.1') INSERT [dbo].[Menus]([MenuID], [ParentID], [Name], [URL]) VALUES (9, 3, 'Sub Menu 3.2', 'Sub Menu 3.2') INSERT [dbo].[Menus]([MenuID], [ParentID], [Name], [URL]) VALUES (10,3, 'Sub Menu 3.2', 'Sub Menu 3.3')
Project Creation
Create a new ASP.NET, C# project. Save it according to your choice. Add a Literal in the master page. This Literal will represent the menu dynamically. We can apply our customize CSS as we want to give nice outlook of the menu.
Create a new ASP.NET, C# project. Save it according to your choice. Add a Literal in the master page. This Literal will represent the menu dynamically. We can apply our customize CSS as we want to give nice outlook of the menu.
Adding a Connection String
we need to add or create a connection string in Web.config file.Add the following element to the <connectionStrings> element in Web.config file:
we need to add or create a connection string in Web.config file.Add the following element to the <connectionStrings> element in Web.config file:
<add name="ConStr" connectionString="Data Source=localhost;Initial Catalog=TestDB;Persist Security Info=True;User ID=sa;Password=sa123" providerName="System.Data.SqlClient"/>
Implement Different Methods
Some methods are required to generate the menu. Implement the following methods in the .cs page of the master page.
Some methods are required to generate the menu. Implement the following methods in the .cs page of the master page.
- GetConnectionStrings
- SelectDataTable
- GenerateMenu
But at first we need to include some namespaces.Please add the following namespaces:
using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Text;
public string GetConnectionStrings() { string ConStr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString; return ConStr; } public DataTable SelectDataTable(String Sql) { DataTable dt = new DataTable(); SqlConnection oSqlConnection = new SqlConnection(GetConnectionStrings()); try { oSqlConnection.Open(); SqlDataAdapter sqlda = new SqlDataAdapter(Sql, GetConnectionStrings()); sqlda.Fill(dt); } catch (Exception ex) { throw new Exception(ex.Message); } finally { oSqlConnection.Close(); oSqlConnection.Dispose(); } return dt; }
private string GenerateMenu(DataRow[] drParentMenu, DataTable oDataTable, StringBuilder oStringBuilder) { oStringBuilder.AppendLine("<ul>"); if (drParentMenu.Length > 0) { foreach (DataRow dr in drParentMenu) { string MenuURL = dr["URL"].ToString(); string MenuName = dr["Name"].ToString(); string line = String.Format(@"<li ><a href=""{0}"">{1}</a>", MenuURL, MenuName); oStringBuilder.Append(line); string MenuID = dr["MenuID"].ToString(); string ParentID = dr["ParentID"].ToString(); DataRow[] subMenu = oDataTable.Select(String.Format("ParentID = {0}", MenuID)); if (subMenu.Length > 0 && !MenuID.Equals(ParentID)) { var subMenuBuilder = new StringBuilder(); oStringBuilder.Append(GenerateMenu(subMenu, oDataTable, subMenuBuilder)); } oStringBuilder.Append("</li>"); } } oStringBuilder.Append("</ul>"); return oStringBuilder.ToString(); }
Generate the Dynamic Menu
Write the following C# code in the Page_Load event of the .cs page of the master page. Here we can pass the user ID of login user in the SQL query:
Write the following C# code in the Page_Load event of the .cs page of the master page. Here we can pass the user ID of login user in the SQL query:
SELECT MenuID, ParentID, Name, URL FROM Menus
We can use where Clause or can apply any customize logic.
We can use another “MenuSettings” table, where user wise permission will be saved. For example: MenuID, UserID
Need to join both “Menus” and “MenuSettings” table.
We can use another “MenuSettings” table, where user wise permission will be saved. For example: MenuID, UserID
Need to join both “Menus” and “MenuSettings” table.
if (!IsPostBack) { DataTable oDataTable = new DataTable(); oDataTable = SelectDataTable("SELECT MenuID, ParentID, Name, URL FROM Menus"); DataRow[] drParentMenu = oDataTable.Select("ParentID = 0"); var oStringBuilder = new StringBuilder(); string MenuList = GenerateMenu(drParentMenu, oDataTable, oStringBuilder); Literal1.Text = MenuList; }
A lot of third party tools are available to create dynamic menus. But most of the time it becomes difficult to customize them according to our requirements. With the help of this tutorial we can easily create dynamic menu in ASP.NET C#. Hope you all enjoy this article.
No comments