Kendo UI TreeList Remote DataBinding With ASP.NET MVC 5 Using ASP.NET WEB API

Introduction
 
In my previous article, I discussed how to work with Kendo UI TreeList basic features. Now, this article will demonstrate you how to construct the Kendo TreeView with complex JSON object, which is the response of the REST API developed using ASP.NET Web API using Entity Framework.Okay! Let us move forward.
 
Prerequisites 
  • Visual Studio
  • SQL Server
  • Basic knowledge of ASP.NET MVC
  • Basic knowledge of ASP.NET Web API
  • Basic knowledge of Entity Framework
  • Basic knowledge of jQuery
  • Basic knowledge of CSS
 
Article Flow 
  • Create a table in a database with dummy values.
  • Create an ASP.NET Web API Empty project
  • Configure Entity Framework with ASP.NET Web API 
  • Create Controller with data Load Logic using Entity Framework in ASP.Net Web API 
  • Test the API Response using POSTMAN
  • Create an ASP.NET MVC Empty project
  • Create a Controller and View
  • Enable Kendo UI Features
  • Kendo Remote Binding in view
Create a table in database with dummy values
 
First, we will create a table in SQL Server to populate a Kendo UI TreeList with data in ASP.NET MVC. I have created a table "Employee" with the following design.
 
 
 
Execute the below query to create a table with the above design. 
  1. CREATE TABLE [dbo].[Employee](  
  2. [ID] [bigint] IDENTITY(1,1) NOT NULL,  
  3. [Name] [nvarchar](150) NULL,  
  4. [Designation] [nvarchar](150) NULL,  
  5. [Location] [nvarchar](50) NULL,  
  6. [TeamLeader] [bigintNULL,  
  7. CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED  
  8. (  
  9.    [ID] ASC  
  10. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  11. ON [PRIMARY]  
  12. GO  
And, insert a few employee records like below.
 
 
 
 Execute the below query to get the same records.
  1. GO  
  2. SET IDENTITY_INSERT [dbo].[Employee] ON  
  3. GO  
  4. INSERT [dbo].[Employee] ([ID], [Name], [Designation], [Location], [TeamLeader]) VALUES (1, N'Gnanavel Sekar', N'Software Engineer', N'Chennai', 4)  
  5. GO  
  6. INSERT [dbo].[Employee] ([ID], [Name], [Designation], [Location], [TeamLeader]) VALUES (2, N'Robert Bellar', N'Software Engineer', N'Chennai', 4)  
  7. GO  
  8. INSERT [dbo].[Employee] ([ID], [Name], [Designation], [Location], [TeamLeader]) VALUES (3, N'Muthu A', N'Software Engineer', N'Chennai', 4)  
  9. GO  
  10. INSERT [dbo].[Employee] ([ID], [Name], [Designation], [Location], [TeamLeader]) VALUES (4, N'Ramar Ammavasi', N'Sr.Software Engineer', N'Chennai'NULL)  
  11. GO  
  12. INSERT [dbo].[Employee] ([ID], [Name], [Designation], [Location], [TeamLeader]) VALUES (5, N'Gokul D', N'Sr.Software Engineer', N'Coimbatore'NULL)  
  13. GO  
  14. INSERT [dbo].[Employee] ([ID], [Name], [Designation], [Location], [TeamLeader]) VALUES (6, N'Karthick', N'Software Engineer', N'Coimbatore', 5)  
  15. GO  
  16. INSERT [dbo].[Employee] ([ID], [Name], [Designation], [Location], [TeamLeader]) VALUES (7, N'Sharma', N'Software Engineer', N'Coimbatore', 5)  
  17. GO  
  18. INSERT [dbo].[Employee] ([ID], [Name], [Designation], [Location], [TeamLeader]) VALUES (8, N'Sheriff', N'Software Engineer', N'Coimbatore', 5)  
  19. GO  
  20. INSERT [dbo].[Employee] ([ID], [Name], [Designation], [Location], [TeamLeader]) VALUES (9, N'Anand s', N'Software Engineer', N'Coimbatore', 5)  
  21. GO  
  22. INSERT [dbo].[Employee] ([ID], [Name], [Designation], [Location], [TeamLeader]) VALUES (10, N'Mubarak', N'Software Engineer', N'Coimbatore', 5)  
  23. GO  
  24. SET IDENTITY_INSERT [dbo].[Employee] OFF  
  25. GO  
Create an ASP.NET Web API Empty project
 
 To create an ASP.NET WEB API empty project, follow the below steps one by one. Here, I have used Visual Studio 2013.
 
Steps :  
  1.  Select New Project -> Visual C# -> Web -> ASP.NET Web Application and enter your application name. Here, I named it "KendoServices". Now, click OK.
  2. Select Empty Web API template and click OK to create the project. 
  3. Once you click OK, the project will be created with the basic architecture of ASP.NET WEB API 
 
Configure Entity Framework with ASP.NET Web API
 
 Here, I already discussed how to configure and implement database first approach. In the meantime choose our created table with entity framework, once we did our configuration with SQL table "Employee" from CRUD database and with our application you will get the below screen as succeeding configuration. 
 
 
 
Create Controller with data Load Logic using Entity Framework in ASP.Net Web API
 
Add an Empty Controller and name it as "KendoServicesController" and load data from database using entity framework to write the below codes to in KendoServices controller.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using System.Web.Http.Description;  
  8. using KendoServices.Models;  
  9. namespace KendoServices.Controllers {  
  10.     public class KendoServicesController: ApiController {  
  11.         [ResponseType(typeof(IEnumerable < Employee > ))]  
  12.         [System.Web.Http.Route("api/GetAllEmployees")]  
  13.         public HttpResponseMessage GetAllEmployees() {  
  14.             CSharpCornerEntities entity = new CSharpCornerEntities();  
  15.             var result = entity.Employees.ToList();  
  16.             return GetResultResponse(result);  
  17.         }  
  18.         /// <summary>  
  19.         /// Get Response for Each result  
  20.         /// </summary>  
  21.         /// <param name="Result"></param>  
  22.         /// <returns></returns>  
  23.         public HttpResponseMessage GetResultResponse(object Result) {  
  24.             HttpResponseMessage response = null;  
  25.             try {  
  26.                 response = Request.CreateResponse(HttpStatusCode.OK, Result);  
  27.             } catch (Exception ex) {  
  28.                 response = Request.CreateResponse(HttpStatusCode.InternalServerError, Result);  
  29.             }  
  30.             return response;  
  31.         }  
  32.     }  
  33. }  
Now Run your service
 
 
If you are getting any error in ASP.NET Web API service, Please refer this Link 
 
Test the API Response using POSTMAN
 
As you can see from the image below it has provided the success response by listing all employee details
 
 
 
Create an ASP.NET MVC Empty project
 
To create ASP.NET MVC empty project, follow the below steps one by one. Here, I have used Visual Studio 2013.
  • Select New Project -> Visual C# -> Web -> ASP.NET Web Application and enter your application name. Here, I named it "KendoServices".Now, click OK.
  • Then, select Empty ASP.Net MVC template and click OK to create the project.
  • Once you click OK, the project will be created with the basic architecture of MVC.If you are not aware of how to create an Empty ASP.NET Web Application, please visit Step 1 and Step 2 to learn.
  • Once you complete these steps you will get the screen as below
 
 Create a Controller and View
 
Now, create an empty Controller and View. Here, I created a Controller with the name of "KendoTreeListController". Whenever we create an empty Controller, it is created with empty Index action method. Also, create an empty View to this action method "Index".
 
Enable Kendo UI Features
 
Here, we are going to enable the Kendo UI features with our application by adding the below CSS and JS in our shared _Layout View. 
  1. <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.common-material.min.css" />  
  2. <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.material.min.css" />  
  3. <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.material.mobile.min.css" />  
  4. <script src="https://kendo.cdn.telerik.com/2017.3.1026/js/jquery.min.js"></script>  
  5. <script src="https://kendo.cdn.telerik.com/2017.3.1026/js/kendo.all.min.js"></script>  
 Kendo Remote Data Binding in view
 
Add the below code to do the remote data binding. In the below code, you can see that the URL is mentioned with ASP.NET Web API service route.
  1. var dataSource = new kendo.data.TreeListDataSource({  
  2.     transport: {  
  3.         read: {  
  4.             url: "http://localhost:42612/api/GetAllEmployees",  
  5.             dataType: "json"  
  6.         }  
  7.     },  
  8.     schema: {  
  9.         model: {  
  10.             id: "ID",  
  11.             parentId: "TeamLeader",  
  12.             fields: {  
  13.                 TeamLeader: {  
  14.                     field: "TeamLeader",  
  15.                     nullable: true  
  16.                 },  
  17.             }  
  18.         }  
  19.     }  
  20. });  
For a clear view, see the below image.
 
 
 
dataSource - The data source of the Kendo TreeView should be a hierarchical data source and it is constructed based on our complex JSON object from API.
 
Now, run your API services and application.
 
 
 
Application Code 
 
Complete View 
  1. @ {  
  2.     ViewBag.Title = "Kendo-TreeList";  
  3. } < body > < div id = "example" > < div id = "treelist"  
  4. style = "width:610px" > < /div> < script id = "photo-template"  
  5. type = "text/x-kendo-template" > < div class = 'employee-photo'  
  6. style = 'background-image: url(../Content/Employees/#:data.ID#.jpg); ' > < /div> < div class = 'employee-name' > #: Name# < /div> < /script> < script > $(document).ready(function() {  
  7.     var dataSource = new kendo.data.TreeListDataSource({  
  8.         transport: {  
  9.             read: {  
  10.                 url: "http://localhost:42612/api/GetAllEmployees",  
  11.                 dataType: "json"  
  12.             }  
  13.         },  
  14.         schema: {  
  15.             model: {  
  16.                 id: "ID",  
  17.                 parentId: "TeamLeader",  
  18.                 fields: {  
  19.                     TeamLeader: {  
  20.                         field: "TeamLeader",  
  21.                         nullable: true  
  22.                     },  
  23.                 }  
  24.             }  
  25.         }  
  26.     });  
  27.     $("#treelist").kendoTreeList({  
  28.         dataSource: dataSource,  
  29.         height: 500,  
  30.         filterable: true,  
  31.         sortable: true,  
  32.         columns: [{  
  33.             field: "Name",  
  34.             expandable: true,  
  35.             title: "Employee Name",  
  36.             width: 230,  
  37.             template: $("#photo-template").html()  
  38.         }, {  
  39.             field: "Designation",  
  40.             title: "Designation",  
  41.             width: 200  
  42.         }, {  
  43.             field: "Location"  
  44.         }]  
  45.     });  
  46. }); < /script> < style > .employee - photo {  
  47.         display: inline - block;  
  48.         width: 32 px;  
  49.         height: 32 px;  
  50.         border - radius: 50 % ;  
  51.         background - size: 32 px 35 px;  
  52.         background - position: center center;  
  53.         vertical - align: middle;  
  54.         line - height: 32 px;  
  55.         box - shadow: inset 0 0 1 px #999, inset 0 0 10px rgba(0,0,0,.2);  
  56. margin-left: 5px;  
  57. }  
  58. .employee-name {  
  59. display: inline-block;  
  60. vertical-align: middle;  
  61. line-height: 32px;  
  62. padding-left: 3px;  
  63. }  
  64. </style>  
  65. </div>  
  66. </body>  
_Layout.cshtml 
  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <meta charset="utf-8" />  
  6.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  7.     <title>@ViewBag.Title - Kendo TreeList</title>  
  8.     <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />  
  9.     <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />  
  10.     <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.common-material.min.css" />  
  11.     <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.material.min.css" />  
  12.     <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.material.mobile.min.css" />  
  13.     <script src="https://kendo.cdn.telerik.com/2017.3.1026/js/jquery.min.js"></script>  
  14.     <script src="https://kendo.cdn.telerik.com/2017.3.1026/js/kendo.all.min.js"></script>  
  15. </head>  
  16.   
  17. <body>  
  18.     <div class="navbar navbar-inverse navbar-fixed-top">  
  19.         <div class="container">  
  20.             <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
  21. <span class="icon-bar"></span>  
  22. <span class="icon-bar"></span>  
  23. <span class="icon-bar"></span>  
  24. </button> @Html.ActionLink("Kendo TreeList Remote DataBinding using ASP.NET Web API in MVC5""Index""Home"nullnew { @class = "navbar-brand" }) </div>  
  25.             <div class="navbar-collapse collapse">  
  26.                 <ul class="nav navbar-nav"></ul>  
  27.             </div>  
  28.         </div>  
  29.     </div>  
  30.     <div class="container body-content"> <br /> @RenderBody()  
  31.         <hr /> </div>  
  32. </body>  
  33.   
  34. </html>  
RouteConfig.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Routing;  
  7. namespace KendoTreeListRemoteDataBinding {  
  8.     public class RouteConfig {  
  9.         public static void RegisterRoutes(RouteCollection routes) {  
  10.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  11.             routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new {  
  12.                 controller = "KendoTreeList", action = "Index", id = UrlParameter.Optional  
  13.             });  
  14.         }  
  15.     }  
  16. }  
API Code - Complete Controller 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using System.Web.Http.Description;  
  8. using KendoServices.Models;  
  9. namespace KendoServices.Controllers {  
  10.     public class KendoServicesController: ApiController {  
  11.         [ResponseType(typeof(IEnumerable < Employee > ))]  
  12.         [System.Web.Http.Route("api/GetAllEmployees")]  
  13.         public HttpResponseMessage GetAllEmployees() {  
  14.             CSharpCornerEntities entity = new CSharpCornerEntities();  
  15.             var result = entity.Employees.ToList();  
  16.             return GetResultResponse(result);  
  17.         }  
  18.         /// <summary>  
  19.         /// Get Response for Each result  
  20.         /// </summary>  
  21.         /// <param name="Result"></param>  
  22.         /// <returns></returns>  
  23.         public HttpResponseMessage GetResultResponse(object Result) {  
  24.             HttpResponseMessage response = null;  
  25.             try {  
  26.                 response = Request.CreateResponse(HttpStatusCode.OK, Result);  
  27.             } catch (Exception ex) {  
  28.                 response = Request.CreateResponse(HttpStatusCode.InternalServerError, Result);  
  29.             }  
  30.             return response;  
  31.         }  
  32.     }  
  33. }  
WebApiConfig.cs 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Routing;  
  7. namespace KendoTreeListRemoteDataBinding {  
  8.     public class RouteConfig {  
  9.         public static void RegisterRoutes(RouteCollection routes) {  
  10.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  11.             routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new {  
  12.                 controller = "KendoTreeList", action = "Index", id = UrlParameter.Optional  
  13.             });  
  14.         }  
  15.     }  
  16. }  
Here, we have created an empty project so it cannot get built in CSS. So, I have attached the respective CSS under a Content folder with employee static photos and referred it to a project. Refer to the attached project for reference. I did attach the demonstrated application and API project. The API project is attached without package for Entity Framework 6.0 due to the size limit.

Summary 
 
We have seen how to construct the Kendo tree view with complex JSON object using ASP.NET Web API and Entity Framework in ASP.NET MVC Web Application.
 
I hope it will help you out. Your valuable feedback and comments about this article are always welcome. 

Up Next
    Ebook Download
    View all
    Learn
    View all