Dynamically-populated-Treeview-in-kendo-using-MVC

Updated : Oct 29, 2019 in Articles

Dynamically populated Treeview in kendo using MVC

In this article, we learn about how to dynamically populated Treeview in kendo using MVC with SQL Server database

Dynamically-populated-Treeview-in-kendo-using-MVC
Dynamically-populated-Treeview-in-kendo-using-MVC

Steps for implementing populated Treeview in kendo using MVC

  1. Create a table in SQL server
  2. Generate an Ado.Net entity data model
  3. Implement the controller and View

Step 1: Create a table in SQL Server

create two tables(Country, State) by using the following given SQL queries and insert some dummy data like country-wise some states

CREATE TABLE [dbo].[Country](
	[PKCountryId] [int] IDENTITY(1,1) NOT NULL,
	[CountryName] [varchar](50) NOT NULL,
	[ZipCodeStart] [bigint] NOT NULL,
	[ZipCodeEnd] [bigint] NOT NULL,
	[IsActive] [bit] NOT NULL,

	)
CREATE TABLE [dbo].[State](
	[PKStateId] [int] IDENTITY(1,1) NOT NULL,
	[FKCountryId] [int] NOT NULL,
	[StateName] [varchar](20) NOT NULL,
	[IsActive] [bit] NOT NULL,
	)

Step 2:Generate an Ado.Net entity data Model

Right-click on your project Add Ado.net entity data Model

Ado.Net entity data Model
Ado.Net entity data Model

Step 3: implementing the controller and view

Go to the home controller Add given below snippet code

 public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View();
        }

        public JsonResult Country_read(int? id)
        {
            using (var Context = new ContactsManagerDBEntities())
            {
                var countryQuery = Context.Countries.Select(c => new HierarchicalViewModel
                {
                    ID = c.PKCountryId,
                    Name = c.CountryName,
                    ParentID = null,
                    HasChildren = c.States.Any()
                })
                .Union(Context.States.Select(c => new HierarchicalViewModel
                {
                    ID = c.PKStateId,
                    Name = c.StateName,
                    ParentID = c.FKCountryId,
                    HasChildren = c.Addresses.Any()
                }));
                var result = countryQuery.ToList()
                 .Where(x => id.HasValue ? x.ParentID == id : x.ParentID == null)
                 .Select(item => new
                 {
                     id = item.ID,
                     Name = item.Name,
                     expanded = item.Expanded,
                     hasChildren = item.HasChildren

                 });

                return Json(result, JsonRequestBehavior.AllowGet);
            }
        }
    }

Add a view for an Index action method following given HTML code

@{
    ViewBag.Title = "Home Page";
}

@(Html.Kendo().Button()
    .Name("expandNode")
    .Content("Expand selected node")
    .Events(e => e.Click("onExpandClick"))
)

@(Html.Kendo().TreeView()
    .Name("treeview")            
    .DataTextField("Name")
    .DataSource(dataSource => dataSource        
        .Read(read => read                   
            .Action("Country_read", "Home")
        )
    )
)

<script>
    function onExpandClick(e) {
        var tree = $("#treeview").data("kendoTreeView"),
            selected = tree.select(),
            dataItem = tree.dataItem(selected);

        var load = function (item) {
            var that = this,
                chain = $.Deferred().resolve();

            chain = chain.then(function () {
                that.expand(that.findByUid(item.uid));
                return item.load();
            }).then(function () {
                if (item.hasChildren) {
                    var childrenChain = $.Deferred().resolve();

                    item.children.data().forEach(function (child) {
                        (function (child) {
                            childrenChain = childrenChain.then(function () {
                                return load.bind(that)(child);
                            })
                        })(child)
                    })

                    return childrenChain;
                }
            });
            return chain;
        }
        if (selected.length == 0) {
            alert("Select item first!");
            return;
        }
        load.bind(tree)(dataItem);
    }
</script>

Like
Like Love Haha Wow Sad Angry
1

10 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Marco Sorokin
January 31, 2020 6:02 pm

These are in fact wonderful ideas in about blogging. You have touched some good points here. Any way keep up wrinting.

Santos
February 15, 2020 7:19 pm

Hello! Do you use Twitter? I’d like to follow you if that would
be okay. I’m definitely enjoying your blog and look forward to new posts.

AmyFax
AmyFax
April 30, 2020 11:49 am

Thank yоu for posting this awesome article.

KimFax
KimFax
April 30, 2020 12:45 pm

Thanks for sharing nice article

jr mreyes
May 2, 2020 9:29 am

Nice article thanks for sharing

sharonda
sharonda
May 2, 2020 12:35 pm

Thanks for sharing article nice and clean

ShattoTaetumnut
ShattoTaetumnut
May 3, 2020 1:51 am

Simply content nice article I bookmarked your site thanks for sharing