Dynamic Column Binding In The Kendo Grid Using ASP.NET Web API

Introduction:

This article tells about how to create a dynamic column binding in Kendo Grid, using ASP.NET WEB API Application. To explain it, I have created a RESTful GET Service, using ASP.NET WEB API, which is used to load the DataSource of Kendo Grid to generate a dynamic column.

Prerequisites

Basic knowledge in ASP.NET WEB API, jQuery, Kendo UI.

This article flows as follows.

  1. Creating an ASP.NET Web API Application.
  2. Creating a Controller.
  3. Testing the REST API.
  4. Construct a Kendo Grid with the dynamic column

Creating an ASP.NET WEB API Application

Create a Web API Application, using an installed Web template in Visual Studio, as shown below. In my case, I named the Application “KendoGridDynamicColumn".

  
                                                                             Figure  1 
 
   
                                                 Figure 2  

Creating model classes

In the Solution Explorer, right click on Models folder, select Add followed by Class and name it as Employee.cs.

  1. public class Employee  
  2.     {  
  3.         public Employee(int Id, string Name, string Designation)  
  4.         {  
  5.             this.EmployeeID = Id;  
  6.             this.EmployeeName = Name;  
  7.             this.Designation = Designation;  
  8.   
  9.         }  
  10.         public int EmployeeID { getset; }  
  11.         public string EmployeeName { getset; }  
  12.         public string Designation { getset; }  
  13.     }  

Creating a Controller

Right click on Controller folder and add a new Web API 2- Empty controller, as shown in the figure 3. In my case, I named it as EmployeeController.cs.

                                                                                             Figure 3 

EmployeeController.cs 

  1. public class EmployeeController : ApiController  
  2.     {  
  3.         [HttpGet]  
  4.         [AllowAnonymous]  
  5.         [Route("EmployeeList")]  
  6.         public HttpResponseMessage GetEmployee()  
  7.         {  
  8.             try  
  9.             {  
  10.                 List<Employee> EmpLists = new List<Employee>();  
  11.                 EmpLists.Add(new Employee(1, "Govind Raj""Business Analyst"));  
  12.                 EmpLists.Add(new Employee(2, "Krishn Mahato""Development"));  
  13.                 EmpLists.Add(new Employee(3, "Bob Ross""Testing"));  
  14.                 EmpLists.Add(new Employee(4, "Steve Davis""Development"));  
  15.                 EmpLists.Add(new Employee(5, "Dave Tucker""Infrastructure"));  
  16.                 EmpLists.Add(new Employee(6, "James Anderson""HR"));  
  17.                 return Request.CreateResponse(HttpStatusCode.OK, EmpLists, Configuration.Formatters.JsonFormatter);  
  18.             }  
  19.             catch (Exception ex)  
  20.             {  
  21.                 return Request.CreateResponse(HttpStatusCode.OK, ex.Message, Configuration.Formatters.JsonFormatter);  
  22.             }  
  23.         }  
  24.     }  

Employee Controller Action GetEmployee will return a list of the employees.

Testing the REST API

Test API, using the POSTMAN/Fiddler, as shown in figure 4.

  • API End Point /api/Employee/EmployeeList.
  • Type GET.
                                                                                                        Figure 4 

Creating a HTML page

Create one new HTML page in the Application, where we are going to construct Kendo Grid with the dynamic column, using the RESTful Service. In my case, I named it as DynamicKendoGrid.html.

Construct a Kendo Grid with dynamic column

Kendo Grid is automatically populated, using the DataSource, which is set; based on the Service, which we are providing

Write the code in newly created HTML page

DynamicKendoGrid.html 
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8">  
  5.     <title>Untitled</title>  
  6.   
  7.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1118/styles/kendo.common.min.css">  
  8.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1118/styles/kendo.rtl.min.css">  
  9.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1118/styles/kendo.default.min.css">  
  10.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1118/styles/kendo.mobile.all.min.css">  
  11.   
  12.     <script src="http://code.jquery.com/jquery-1.12.3.min.js"></script>  
  13.     <script src="http://kendo.cdn.telerik.com/2016.3.1118/js/angular.min.js"></script>  
  14.     <script src="http://kendo.cdn.telerik.com/2016.3.1118/js/jszip.min.js"></script>  
  15.     <script src="http://kendo.cdn.telerik.com/2016.3.1118/js/kendo.all.min.js"></script>  
  16. </head>  
  17. <body>  
  18. <h3> Dynamic Column Binding in the kendo Grid</h3>  
  19.     <div id="grid" style="width:600px;"></div>  
  20. </body>  
  21.   
  22. </html>  
  23. <script type="text/javascript">  
  24.     var dateFields=[];  
  25.     $(document).ready(function () {  
  26.         $.ajax({  
  27.             url: "/api/Employee/EmployeeList",  
  28.             success:function(result)  
  29.             {                                       
  30.                 generateGrid(result);  
  31.                   
  32.             },  
  33.            error:function()
  34.            {
  35.                 alert("Some error has occurred");     
  36.             }
  37.         })  
  38.           
  39.   
  40.     })  
  41.     function generateGrid(gridData) {  
  42.         debugger;  
  43.         var model = generateModel(gridData[0]);             
  44.         var grid = $("#grid").kendoGrid({  
  45.             dataSource: {  
  46.                 data: gridData,  
  47.                    model: model,                    
  48.                             },  
  49.             editable: true,  
  50.             sortable: true,  
  51.         });  
  52.   
  53.     }  
  54.   
  55.     function generateModel(gridData) {  
  56.         var model = {};  
  57.         model.id = "EmployeeID";  
  58.         var fields = {};  
  59.         for (var property in gridData) {  
  60.             var propType = typeof gridData[property];  
  61.             if (propType == "number") {  
  62.                 fields[property] = {  
  63.                     type: "number",  
  64.                     validation: {  
  65.                         required: true  
  66.                     }  
  67.                 };  
  68.             } else if (propType == "boolean") {  
  69.                 fields[property] = {  
  70.                     type: "boolean",  
  71.                     validation: {  
  72.                         required: true  
  73.                     }  
  74.                 };  
  75.             } else if (propType == "string") {  
  76.                 var parsedDate = kendo.parseDate(gridData[property]);  
  77.                 if (parsedDate) {  
  78.                     fields[property] = {  
  79.                         type: "date",  
  80.                         validation: {  
  81.                             required: true  
  82.                         }  
  83.                     };  
  84.                     dateFields.push(property);  
  85.                 } else {  
  86.                     fields[property] = {  
  87.                         validation: {  
  88.                             required: true  
  89.                         }  
  90.                     };  
  91.                 }  
  92.             } else {  
  93.                 fields[property] = {  
  94.                     validation: {  
  95.                         required: true  
  96.                     }  
  97.                 };  
  98.             }  
  99.   
  100.         }  
  101.         model.fields = fields;  
  102.   
  103.         return model;  
  104.     }  
  105.   
  106.       
  107. </script>  

From the code mentioned above, you can observe following functionalities to construct the dynamic grid.

  1. AJAX call is passed when the page loads to get the response from the API service and the grid generation function is called when AJAX call is completed successfully
  2. generateGrid function is used to construct the grid, which is based on the response from the Service.
  3. generateModel function is used to generate the model for the Grid to load its schema.
Result 
 
                            
                                                                  Figure 5
 

Let us now deal with the column generation in Kendo Grid. Write the code, mentioned below in DynamicKendoGrid.html 

  1. function ColumnGeneration(gridData)  
  2.     {  
  3.         var gridObj = gridData[0];  
  4.         GridTitleArray = [];  
  5.         debugger;  
  6.         $.each(gridObj, function (gridTitle, element) {  
  7.             GridTitleArray.push(gridTitle)  
  8.         });  
  9.         GridColumnGeneration = [];  
  10.         for(var i=0;i<GridTitleArray.length;i++)  
  11.         {  
  12.             debugger;  
  13.             if (GridTitleArray[i] == 'EmployeeName')  
  14.             {  
  15.                 GridColumnGeneration.push({ title: GridTitleArray[i], field: GridTitleArray[i], template: '<a onclick="rowFunction()" href="\\#">#=EmployeeName#</a>' })  
  16.             }  
  17.             else{  
  18.                 GridColumnGeneration.push({ title: GridTitleArray[i], field: GridTitleArray[i] })  
  19.             }  
  20.   
  21.         }  
  22.         return GridColumnGeneration;  
  23.    }  

This ColumnGeneration function is used to customize the dynamic column, where you can notice from the code, mentioned above, where I have created a template for the EmployeeName field to make it as a link.

Complete code in DynamicKendoGrid.html is given below.

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8">  
  5.     <title>Untitled</title>  
  6.   
  7.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1118/styles/kendo.common.min.css">  
  8.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1118/styles/kendo.rtl.min.css">  
  9.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1118/styles/kendo.default.min.css">  
  10.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1118/styles/kendo.mobile.all.min.css">  
  11.   
  12.     <script src="http://code.jquery.com/jquery-1.12.3.min.js"></script>  
  13.     <script src="http://kendo.cdn.telerik.com/2016.3.1118/js/angular.min.js"></script>  
  14.     <script src="http://kendo.cdn.telerik.com/2016.3.1118/js/jszip.min.js"></script>  
  15.     <script src="http://kendo.cdn.telerik.com/2016.3.1118/js/kendo.all.min.js"></script>  
  16. </head>  
  17. <body>  
  18.     <h3> Dynamic Column Binding in the kendo Grid</h3>  
  19.     <div id="grid" style="width:600px;"></div>  
  20. </body>  
  21.   
  22. </html>  
  23. <script type="text/javascript">  
  24.     var dateFields=[];  
  25.     $(document).ready(function () {  
  26.         $.ajax({  
  27.             url: "/api/Employee/EmployeeList",  
  28.             success:function(result)  
  29.             {                                       
  30.                 generateGrid(result);  
  31.                  
  32.             },
  33.             error: function()
  34.             {
  35.                alert("Some error has occurred");
  36.              }
  37.  
  38.         })  
  39.          
  40.           
  41.   
  42.     })  
  43.     function generateGrid(gridData) {  
  44.           
  45.         var model = generateModel(gridData[0]);             
  46.         $("#grid").kendoGrid({  
  47.             dataSource: {  
  48.                 data: gridData,  
  49.                  model: model,                               
  50.             },  
  51.             selectable: true,  
  52.             pageable:{  
  53.                 pageSize:5  
  54.             },  
  55.             sortable: true,  
  56.          columns: ColumnGeneration(gridData),  
  57.         }).data('kendoGrid');  
  58.   
  59.     }  
  60.   
  61.     function generateModel(gridData) {  
  62.         var model = {};  
  63.         model.id = "EmployeeID";  
  64.         var fields = {};  
  65.         for (var property in gridData) {  
  66.             var propType = typeof gridData[property];  
  67.             if (propType == "number") {  
  68.                 fields[property] = {  
  69.                     type: "number",  
  70.                     validation: {  
  71.                         required: true  
  72.                     }  
  73.                 };  
  74.             } else if (propType == "boolean") {  
  75.                 fields[property] = {  
  76.                     type: "boolean",  
  77.                     validation: {  
  78.                         required: true  
  79.                     }  
  80.                 };  
  81.             } else if (propType == "string") {  
  82.                 var parsedDate = kendo.parseDate(gridData[property]);  
  83.                 if (parsedDate) {  
  84.                     fields[property] = {  
  85.                         type: "date",  
  86.                         validation: {  
  87.                             required: true  
  88.                         }  
  89.                     };  
  90.                     dateFields.push(property);  
  91.                 } else {  
  92.                     fields[property] = {  
  93.                         validation: {  
  94.                             required: true  
  95.                         }  
  96.                     };  
  97.                 }  
  98.             } else {  
  99.                 fields[property] = {  
  100.                     validation: {  
  101.                         required: true  
  102.                     }  
  103.                 };  
  104.             }  
  105.   
  106.         }  
  107.         model.fields = fields;  
  108.   
  109.         return model;  
  110.     }  
  111.   
  112.     function ColumnGeneration(gridData)  
  113.     {  
  114.         var gridObj = gridData[0];  
  115.         GridTitleArray = [];  
  116.           
  117.         $.each(gridObj, function (gridTitle, element) {  
  118.             GridTitleArray.push(gridTitle)  
  119.         });  
  120.         GridColumnGeneration = [];  
  121.         for(var i=0;i<GridTitleArray.length;i++)  
  122.         {  
  123.           
  124.             if (GridTitleArray[i] == 'EmployeeName')  
  125.             {  
  126.                 GridColumnGeneration.push({ title: GridTitleArray[i], field: GridTitleArray[i], template: '<a onclick="rowFunction()" href="\\#">#=EmployeeName#</a>' })  
  127.             }  
  128.             else{  
  129.                 GridColumnGeneration.push({ title: GridTitleArray[i], field: GridTitleArray[i] })  
  130.             }  
  131.   
  132.         }  
  133.         return GridColumnGeneration;  
  134.   
  135.     }  
  136.     function rowFunction()  
  137.     {  
  138.         alert("hello!!")  
  139.     }  
  140. </script>   
Result
 
  
                                                                           Figure 6 
 
                                                                                               Figure 7
 
 I hope, you have enjoyed this article. Your valuable feedback, questions or comments about this article are always welcome.
 
 Get the source code from GitHub.

Up Next
    Ebook Download
    View all
    Learn
    View all