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

TreeView is one of the easiest and fastest site navigation menus. Its used to display hierarchical data in a tree structure. In this post, I will explain how to create treeview with database data in MVC 4 application. There's no "ready to use" control or mvc helper for render data as treeview in MVC. So, Here I have created a very simple helper for render database data in tree structure and used a little jquery for collapse and expand treeview.
How to create treeview with database data in MVC 4 application.
@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>
}






Posted By :