Click here to Skip to main content
15,891,567 members
Articles / Web Development / ASP.NET

Creating Dynamics Tree View Menu in ASP.NET MVC 4 in a Dirty Way

Rate me:
Please Sign up or sign in to vote.
4.63/5 (19 votes)
10 Feb 2016CPOL5 min read 53.8K   24   13
This tip describes how to create dynamics tree view in ASP.NET MVC 4 in a dirty way; create and render the DOM string.

Introduction

In this article, we will create dynamics tree view menu using ASP.NET MVC 4, C#, Razor and of course, SQL Server (I use Visual Studio 2015 Community Edition and SQL Server 2012 Express). We will populate menu items (menu names, URIs, and icons) from our SQL table Menu into a .NET datatable and manipulate it into DOM string, and then render it with Razor function @Html.Raw() in the View code. The word "dynamics" here indicates that we can create multilevel tree view menu, no matter how many tree levels there are. We will do it in a dirty-simple way; with this method, we can get multi-level tree view menu, not only -hardcoded- two or three tree levels like you see in many tutorials.

Background

In a web application, especially for admin web applications, we have to create a tree view menu, maybe in a sidebar or the header of our web application. Instead of hardcoding the tree view menu in the View, we can create it dynamically, populate the menu item from table Menu in database, and then render it in View. In this article, we will use ASP.NET MVC 4 (using C#) empty template to demonstrate how to create dynamic tree view menus from scratch. You can modify and simplify this source code whenever you want.

Preparation

Before we go far, we create table Menu in database (in your existing database, or you can create a new one), the table structure is shown below, column Id is the primary key, and set it auto-increment.

Image 1

This is the script to create the table:

SQL
CREATE TABLE [dbo].[Menu] (
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[MenuNumber] [int] NOT NULL,
	[ParentNumber] [int] NULL,
	[MenuName] [varchar](50) NOT NULL,
	[Uri] [varchar](50) NULL,
	[Icon] [varchar](50) NOT NULL,
 CONSTRAINT [PK_Menu] PRIMARY KEY CLUSTERED 
 ( [Id] ASC ) 
  WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
	     IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
	     ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]
) ON [PRIMARY]

And then, insert the table with some values, the table will look like this:

Image 2

This is the script to insert table Menu to get the result like the picture above:

SQL
INSERT INTO [dbo].[Menu]([MenuNumber], [ParentNumber], [MenuName], [Uri], [Icon])
VALUES(0, NULL, 'MAIN NAVIGATION', '', 'glyphicon glyphicon-dashboard')

INSERT INTO [dbo].[Menu]([MenuNumber], [ParentNumber], [MenuName], [Uri], [Icon])
VALUES(1000, 0, 'Dashboard', 'dashboard', 'glyphicon glyphicon-dashboard')

INSERT INTO [dbo].[Menu]([MenuNumber], [ParentNumber], [MenuName], [Uri], [Icon])
VALUES(2000, 0, 'User', '', 'glyphicon glyphicon-user')

INSERT INTO [dbo].[Menu]([MenuNumber], [ParentNumber], [MenuName], [Uri], [Icon])
VALUES(3000, 0, 'Setting', '', 'glyphicon glyphicon-cog')

INSERT INTO [dbo].[Menu]([MenuNumber], [ParentNumber], [MenuName], [Uri], [Icon])
VALUES(2010, 2000, 'Profile', 'user/profile', 'glyphicon glyphicon-sunglasses')

INSERT INTO [dbo].[Menu]([MenuNumber], [ParentNumber], [MenuName], [Uri], [Icon])
VALUES(2020, 2000, 'My File', 'user/myfile', 'glyphicon glyphicon-folder-open')

INSERT INTO [dbo].[Menu]([MenuNumber], [ParentNumber], [MenuName], [Uri], [Icon])
VALUES(2021, 2020, 'Document', 'user/myfile/document', 'glyphicon glyphicon-folder-close')

INSERT INTO [dbo].[Menu]([MenuNumber], [ParentNumber], [MenuName], [Uri], [Icon])
VALUES(2022, 2020, 'Music', 'user/myfile/music', 'glyphicon glyphicon-music')

INSERT INTO [dbo].[Menu]([MenuNumber], [ParentNumber], [MenuName], [Uri], [Icon])
VALUES(3010, 3000, 'General Setting', 'setting/general', 'glyphicon glyphicon-wrench')

INSERT INTO [dbo].[Menu]([MenuNumber], [ParentNumber], [MenuName], [Uri], [Icon])
VALUES(3020, 3000, 'Privacy', 'setting/privacy', 'glyphicon glyphicon-lock')

Note that, when a menu doesn't have any parent number (NULL), then that menu is the (outer) parent of all menus. Here, for the child menus, we use menu number 1000, for example. It has parent number 0 and it has child numbers 1010, 1020, 1030, and so on; and when a menu with number 1020 has child menu, its child menu number will be 1021, 1022, and so on; and when menu number 1021 has children, the child number will be 10211, 10212, and so on; and so on. This is just a convention, you can use your own menu numbering.

Using the Code

We already have the table Menu in our database, we also have the data. Now, we can write the source code. First, open Visual Studio and then create a new project with template Visual C# - ASP.NET Web Application, name the project TreeViewMenu. Select the Empty template with add folder and core references for MVC. Visual Studio will create the empty template MVC for us.

Image 3

Create a controller in folder Controllers, name it HomeController. Then, right click in method ActionResult Index() and Add a View for it, name the view Index. Overwrite the view Index.cshtml (in folder ~/Views/Home) with this code:

ASP.NET
@{
	Layout = null;
}
<!DOCTYPE html>
<html>
<head>
	<meta name="viewport" content="width=device-width" />
	<title>Index</title>

	<link href="~/Contents/css/bootstrap.css" rel="stylesheet" type="text/css" />
</head>
<body>
	<div> 
	   @Html.Raw(ViewBag.DOM_TreeViewMenu)
	</div>
	
	<script src="~/Contents/js/jquery-1.11.3.min.js" type="text/javascript"></script>
	<script src="~/Contents/js/bootstrap.js" type="text/javascript"></script>
</body>
</html>

Save the file. In the center of cshtml code above, you can see the razor function (or helper) @Html.Raw(), this function will render a raw string of HTML code (DOM) when you open it in your web browser. Next, we will set the value of object ViewBag.DOM_TreeViewMenu with raw HTML code of tree view menu in our HomeController.

Now, we can go to folder Contents, add folder css, fonts, and js in that folder. We use standard bootstrap, glyphicons font and jQuery (you can download it for free). Here, we only need to get the glyphicon to demonstrate tree view menu with icon. In Solution Explorer, you can see the structure of folder Contents is like this picture.

Image 4

In HomeController, we create three private methods. see this skeleton code.

C#
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web.Mvc;

namespace TreeViewMenu.Controllers
{
    public class HomeController : Controller
    {
        private SqlConnection conn;
        private SqlDataAdapter da;
        private DataTable dt;

        public ActionResult Index()
        {
            ViewBag.DOM_TreeViewMenu = PopulateMenuDataTable();

            return View();
        }

        private string PopulateMenuDataTable()
        {
            string DOM = "";

            //Do some task here

            return DOM;
        }

        private string GetDOMTreeView(DataTable dt)
        {
            string DOMTreeView = "";

            //Do some task here

            return DOMTreeView;
        }

        private string CreateTreeViewOuterParent(DataTable dt)
        {
            string DOMDataList = "";

            //Do some task here

            return DOMDataList;
        }

        private string CreateTreeViewMenu(DataTable dt, string ParentNumber)
        {
            string DOMDataList = "";

            //Do some task here

            return DOMDataList;
        }
    }
}

We start from method PopulateMenuDataTable(). Here, we will populate data from our SQL table Menu into DataTable. This is the code.

C#
private string PopulateMenuDataTable()
{
	string DOM = "";

	string sql = @"SELECT MenuNumber, ParentNumber, MenuName, Uri, Icon FROM Menu";
	conn = new SqlConnection(@"Data Source = YOUR_SERVERNAME; 
	                                Initial Catalog = YOUR_DATABASE; 
	                                User ID = sa; Password = YOUR_PASSWORD");
	conn.Open();
	
	da = new SqlDataAdapter(sql, conn);
	da.SelectCommand.CommandTimeout = 10000;
	
	dt = new DataTable();
	da.Fill(dt);

	if (conn.State == ConnectionState.Open)
	{
		conn.Close();
	}
	conn.Dispose();

	DOM = GetDOMTreeView(dt);

	return DOM;
}

Then to get the DOM string of the tree view, we write the body of method GetDOMTreeView() and two other methods.

C#
private string GetDOMTreeView(DataTable dt)
{
	string DOMTreeView = "";

	DOMTreeView += CreateTreeViewOuterParent(dt);
	DOMTreeView += CreateTreeViewMenu(dt, "0");

	DOMTreeView += "</ul>";
	
	return DOMTreeView;
}

We populate the DOM string for header (Outer Parent Menu) from method CreateTreeViewOuterParent().

C#
private string CreateTreeViewOuterParent(DataTable dt)
{
	string DOMDataList = "";

	DataRow[] drs = dt.Select("MenuNumber = 0");

	foreach (DataRow row in drs)
	{
		//row[2], 2 is column number start with 0, which is the MenuName
		DOMDataList = "<ul><li class='header'>" + row[2].ToString() + "</li>";
	}

	return DOMDataList;
}

And then, we populate all DOM strings from table Menu, we do it recursively in method CreateTreeViewMenu(), you can look at the method body that the method calls itself in order to get all tree levels from table Menu. As you can also see, we use Lambda expression to filter result of datatable and then store the value into DataRow[], so we can loop the DataRows and get the value easily.

C#
private string CreateTreeViewMenu(DataTable dt, string ParentNumber)
{
	string DOMDataList = "";

	string menuNumber = "";
	string menuName = "";
	string uri = "";
	string icon = "";

	DataRow[] drs = dt.Select("ParentNumber = " + ParentNumber);

	foreach (DataRow row in drs)
	{
		menuNumber = row[0].ToString();
		menuName = row[2].ToString();
		uri = row[3].ToString();
		icon = row[4].ToString();

		DOMDataList += "<li class='treeview'>";
		DOMDataList += "<a href='" + uri + "'><i class='" + icon + "'></i><span>  " 
		                + menuName + "</span></a>";

		DataRow[] drschild = dt.Select("ParentNumber = " + menuNumber);
		if (drschild.Count() != 0)
		{
			DOMDataList += "<ul class='treeview-menu'>";
			DOMDataList += CreateTreeViewMenu(dt, menuNumber).Replace
                           ("<li class='treeview'>", "<li>");
			DOMDataList += "</ul></li>";
		}
		else
		{
			DOMDataList += "</li>";
		}
	}
	return DOMDataList;
}

That's all! Debug the project (I use Google Chrome) and we will get the result like this picture. As you can see, Menu Name and its Icon are shown; and if you point your pointer to a Menu (let's say My File), you can see that the Uri is also successfully loaded to View.

Image 5

If we want to add a child menu, let's say for menu Music, name it Dangdut. We only need to insert it into our table Menu, and no need to change our source code. To demonstrate it, use this script to insert menu Dangdut.

SQL
INSERT INTO [dbo].[Menu]([MenuNumber], [ParentNumber], [MenuName], [Uri], [Icon])
VALUES(20221, 2022, 'Dangdut', 'https://en.wikipedia.org/wiki/Dangdut', _
       'glyphicon glyphicon-globe')

Now, the result will look like this:

Image 6

Points of Interest

This is a dirty way of creating Tree View Menu in ASP.NET MVC, instead of using DOM string like this, you can reduce source code's line with a clean code by manipulating the DOM string using useful List. In real web application, tree view menu is in a master layout View, so you can create a layout view in Shared folder that contains a View with the tree view menu code. With a little enhancement with bootstrap and jQuery or some layout template in our code, we can create a classy navigation tree view menu in our web application.

History

  • 10th February, 2016: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer
Indonesia Indonesia
-

Comments and Discussions

 
QuestionCan i have the project please Pin
Member 1167638224-Mar-20 21:39
Member 1167638224-Mar-20 21:39 
QuestionHOW TO GET THE SELECTED ID Pin
Member 137119991-Jul-18 21:42
Member 137119991-Jul-18 21:42 
GeneralMy vote of 5 Pin
Viadi22-Mar-16 16:20
Viadi22-Mar-16 16:20 
QuestionPosting of actual MVC Project Pin
Corvallis9-Mar-16 8:11
Corvallis9-Mar-16 8:11 
QuestionWhy u use @Html.Raw() ? Pin
Tridip Bhattacharjee10-Feb-16 20:47
professionalTridip Bhattacharjee10-Feb-16 20:47 
AnswerRe: Why u use @Html.Raw() ? Pin
Garbel Nervadof11-Feb-16 4:40
professionalGarbel Nervadof11-Feb-16 4:40 
GeneralRe: Why u use @Html.Raw() ? Pin
Tridip Bhattacharjee11-Feb-16 21:49
professionalTridip Bhattacharjee11-Feb-16 21:49 
GeneralRe: Why u use @Html.Raw() ? Pin
Garbel Nervadof11-Feb-16 23:01
professionalGarbel Nervadof11-Feb-16 23:01 
That's true Tridip, but it depends on what you do with the helper @Html.Raw().
If you are displaying non-user entered data into your web browser, like the tree view menu above, then -Afaik- it's safe to use it.
But if you want to render -let's say- input text box, I think it's not wise to use @Html.Raw()..
Some people consider to use Html.Encode(), please check this out: [MSDN: Html.Encode()]

Cmiiw..
Nice to share.. Smile | :)
GeneralRe: Why u use @Html.Raw() ? Pin
Tridip Bhattacharjee12-Feb-16 0:09
professionalTridip Bhattacharjee12-Feb-16 0:09 
AnswerRe: Why u use @Html.Raw() ? Pin
Member 1269354031-Mar-17 3:12
Member 1269354031-Mar-17 3:12 
GeneralMy vote of 4 Pin
Santhakumar M10-Feb-16 7:32
professionalSanthakumar M10-Feb-16 7:32 
GeneralRe: My vote of 4 Pin
Garbel Nervadof10-Feb-16 15:16
professionalGarbel Nervadof10-Feb-16 15:16 
GeneralRe: My vote of 4 Pin
Santhakumar M12-Feb-16 2:22
professionalSanthakumar M12-Feb-16 2:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.