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>

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *