-->

How to create treeview with database data in MVC 4 application.


Introduction

In the previous article, I have shown you how to implement treeview in asp.net webform application.
In this post, I am going to explain how to create treeview with database data in MVC application.

The ASP.NET TreeView control makes it easy for us to display a hierarchical collection of labeled items, but MVC does not support server-side control like ASP.NET. Also, There is no any HTML helper class method that will provide treeview for the UI. Today I will show you, how to create treeview in MVC application.

Here in this application we will create our own custom HTML helper for display hierarchical data in treeview.

Steps :

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > OK

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for fetch data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used one tables as below

Structure
Database Data


Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a new ASP.NET folder "App_Code"

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > Add ASP.NET Folder > App_Code

Step-6: Create a custom HTML Helpers

Right Click on App_Code folder under Solution Explorer > Add > New Item > Select MVC4 View Page (Rozar) > Enter Name (here "Treeview.cshtml") > Add.
Write this below code to your newly created view under App_Code folder.

@helper GetTreeView(List<MVCTreeview.SiteMenu> siteMenu, int parentID){
    foreach (var i in siteMenu.Where(a=>a.ParentMenuID.Equals(parentID)))
    {
        <li>
            @{var submenu = siteMenu.Where(a => a.ParentMenuID.Equals(i.MenuID)).Count();}
            @if (submenu > 0)
            {
            <span class="collapse collapsible">&nbsp;</span>
            }
            else
            {
                <span style="width:15px; display:inline-block">&nbsp;</span>
            }
            <span>
                <a href="@i.NavURL">@i.MenuName</a>
            </span>
            @if (submenu > 0)
            {
                <ul>
                    @Treeview.GetTreeView(siteMenu,i.MenuID) 
                    @* Recursive  Call for Populate Sub items here*@
                </ul>
            }
        </li>
    }
}

Step-7: Add a new Controller .

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Step-8: Add new action into your controller for Get Method

Here I have added "simple" Action into "Treeview" Controller. Please write this following code

public ActionResult Simple()
{
    List<SiteMenu> all = new List<SiteMenu>();
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        all = dc.SiteMenus.OrderBy(a => a.ParentMenuID).ToList();
    }
    return View(all);
}

Step-9: Add view for this Action & design.

Right Click on Action Method (here right click on form action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Add. [N:B:Please Rebuild solution before add view.]
HTML Code
@model List<MVCTreeview.SiteMenu>
@{
    ViewBag.Title = "Simple";
}
<h2>Simple Treeview from Database Data</h2>
<div style="border:solid 1px black; padding:10px; background-color:#FAFAFA">
    <div class="treeview">
        @if (Model != null && Model.Count() >0)
        {
            <ul>
                @Treeview.GetTreeView(Model, Model.FirstOrDefault().ParentMenuID)
            </ul>
        }
    </div>
</div>
CSS Code
<style>
/*Here We will add some css for style our treeview*/
.collapse {
    width:15px;
    background-image: url('../Images/ui-icons_454545_256x240.png');
    background-repeat: no-repeat;
    background-position: -36px -17px;
    display:inline-block;
    cursor:pointer;
}
.expand {
    width: 15px;
    background-image: url('../Images/ui-icons_454545_256x240.png');
    background-repeat: no-repeat;
    background-position: -50px -17px;
    display: inline-block;
    cursor:pointer;
}
    
    .treeview ul
    {
        font:14px Arial, Sans-Serif;
        margin:0px;
        padding-left:20px;
        list-style:none;
    }
    .treeview > li > a {
        font-weight:bold;
    }
    .treeview li
    {
               
    }
    .treeview li a
    {
        padding:4px;
        font-size:12px;
        display:inline-block;
        text-decoration:none;
        width:auto;
    }
</style>

Here is the Image used in css :       


JS Code
<script>
    $(document).ready(function () {
        $(".treeview li>ul").css('display', 'none'); // Hide all 2-level ul 
        $(".collapsible").click(function (e) {
            e.preventDefault();
            $(this).toggleClass("collapse expand");
            $(this).closest('li').children('ul').slideToggle();
        });
    });
</script>
Complete View
@model List<MVCTreeview.SiteMenu>
@{
    ViewBag.Title = "Simple";
}
<style>
    /*Here We will add some css for style our treeview*/
    .collapse {
        width:15px;
        background-image: url('../Images/ui-icons_454545_256x240.png');
        background-repeat: no-repeat;
        background-position: -36px -17px;
        display:inline-block;
        cursor:pointer;
    }
    .expand {
        width: 15px;
        background-image: url('../Images/ui-icons_454545_256x240.png');
        background-repeat: no-repeat;
        background-position: -50px -17px;
        display: inline-block;
        cursor:pointer;
    }
    
        .treeview ul
        {
            font:14px Arial, Sans-Serif;
            margin:0px;
            padding-left:20px;
            list-style:none;
        }
        .treeview > li > a {
            font-weight:bold;
        }
        .treeview li
        {
               
        }
        .treeview li a
        {
            padding:4px;
            font-size:12px;
            display:inline-block;
            text-decoration:none;
            width:auto;
        }
</style>
<h2>Simple Treeview from Database Data</h2>
<div style="border:solid 1px black; padding:10px; background-color:#FAFAFA">
    <div class="treeview">
        @if (Model != null && Model.Count() >0)
        {
            <ul>
                @Treeview.GetTreeView(Model, Model.FirstOrDefault().ParentMenuID)
            </ul>
        }
    </div>
</div>

@* Here We need some Jquery code for make this treeview collapsible *@
@section Scripts{
    <script>
        $(document).ready(function () {
            $(".treeview li>ul").css('display', 'none'); // Hide all 2-level ul 
            $(".collapsible").click(function (e) {
                e.preventDefault();
                $(this).toggleClass("collapse expand");
                $(this).closest('li').children('ul').slideToggle();
            });
        });
    </script>
}

Step-10: Run Application.

Must see next : How to Populate Treeview Nodes Dynamically (On Demand) using Ajax in ASP.NET

Download Application     Live Demo




  1. How to Populate Treeview Nodes Dynamically (On Demand) using Ajax in ASP.NET
  2. How to Bind Treeview from database using recursion function in asp.net c#?


Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.