Customize Row In Dynamic Kendo Grid On DataBound Event

Introduction

This article tells how to customize a dynamic Kendo Grid row in databound event, 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 of ASP.NET WEB API, jQuery, and 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. Constructing a Kendo Grid with the dynamic column
  5. Customizing the Kendo Grid row

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 as “KendoGridDynamicColumn".

 
 
 

Creating model classes

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

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

Creating a Controller

Right click on the "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".



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

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

Testing the REST API

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

  • API End Point    /api/Employee/EmployeeList.
  • Type    GET.
 
 
Creating an 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 CustomRowKendoGrid.html.

Construct a Kendo Grid with dynamic column

Kendo Grid is automatically populated using the DataSource, which is set based on the Service we are providing. Write the code in newly created HTML page.

CustomRowKendoGrid.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.   
  25.     var dateFields=[];  
  26.     $(document).ready(function () {  
  27.         $.ajax({  
  28.             url: "/api/Employee/EmployeeList",  
  29.             success:function(result)  
  30.             {  
  31.                 generateGrid(result);  
  32.   
  33.             },  
  34.            error:function()  
  35.            {  
  36.                 alert("Some error has occurred");  
  37.             }  
  38.         })  
  39.   
  40.   
  41.     })  
  42.     function generateGrid(gridData) {  
  43.         debugger;  
  44.         var model = generateModel(gridData[0]);  
  45.         var grid = $("#grid").kendoGrid({  
  46.             dataSource: {  
  47.                 data: gridData,  
  48.                    model: model,  
  49.                             },  
  50.             editable: true,  
  51.             sortable: true,  
  52.              
  53.         });  
  54.   
  55.     }  
  56.   
  57.     function generateModel(gridData) {  
  58.         var model = {};  
  59.         model.id = "EmployeeID";  
  60.         var fields = {};  
  61.         for (var property in gridData) {  
  62.             var propType = typeof gridData[property];  
  63.             if (propType == "number") {  
  64.                 fields[property] = {  
  65.                     type: "number",  
  66.                     validation: {  
  67.                         required: true  
  68.                     }  
  69.                 };  
  70.             } else if (propType == "boolean") {  
  71.                 fields[property] = {  
  72.                     type: "boolean",  
  73.                     validation: {  
  74.                         required: true  
  75.                     }  
  76.                 };  
  77.             } else if (propType == "string") {  
  78.                 var parsedDate = kendo.parseDate(gridData[property]);  
  79.                 if (parsedDate) {  
  80.                     fields[property] = {  
  81.                         type: "date",  
  82.                         validation: {  
  83.                             required: true  
  84.                         }  
  85.                     };  
  86.                     dateFields.push(property);  
  87.                 } else {  
  88.                     fields[property] = {  
  89.                         validation: {  
  90.                             required: true  
  91.                         }  
  92.                     };  
  93.                 }  
  94.             } else {  
  95.                 fields[property] = {  
  96.                     validation: {  
  97.                         required: true  
  98.                     }  
  99.                 };  
  100.             }  
  101.   
  102.         }  
  103.         model.fields = fields;  
  104.   
  105.         return model;  
  106.     }  
  107.   
  108. </script>    

From the code mentioned above, you can observe the 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
 
 
Customizing the Kendo Grid row

The Kendo Grid construction is completed. Now, we can start with customizing the row in the Kendo Grid. We can customize the Kendo Grid row in two ways - 1) During Databinding and 2) During Databound event. In this article, I will explain how we can customize the row during the Databound event.

Please go through my previous article to get an idea about Events in Kendo Grid.

CustomRowKendoGrid.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> Customize Row in Dynamic kendo Grid</h3>  
  19.     <div id="grid" style="width:600px;"></div>  
  20. </body>  
  21.   
  22. </html>  
  23. <script type="text/javascript">  
  24.   
  25.     var dateFields=[];  
  26.     $(document).ready(function () {  
  27.         $.ajax({  
  28.             url: "/api/Employee/EmployeeList",  
  29.             success:function(result)  
  30.             {  
  31.                 generateGrid(result);  
  32.   
  33.             },  
  34.            error:function()  
  35.            {  
  36.                 alert("Some error has occurred");  
  37.             }  
  38.         })  
  39.   
  40.   
  41.     })  
  42.     function generateGrid(gridData) {  
  43.         debugger;  
  44.         var model = generateModel(gridData[0]);  
  45.         var grid = $("#grid").kendoGrid({  
  46.             dataSource: {  
  47.                 data: gridData,  
  48.                    model: model,  
  49.                             },  
  50.             editable: true,  
  51.             sortable: true,  
  52.             dataBound: OnGridDataBound,  
  53.         });  
  54.   
  55.     }  
  56.   
  57.     function generateModel(gridData) {  
  58.         var model = {};  
  59.         model.id = "EmployeeID";  
  60.         var fields = {};  
  61.         for (var property in gridData) {  
  62.             var propType = typeof gridData[property];  
  63.             if (propType == "number") {  
  64.                 fields[property] = {  
  65.                     type: "number",  
  66.                     validation: {  
  67.                         required: true  
  68.                     }  
  69.                 };  
  70.             } else if (propType == "boolean") {  
  71.                 fields[property] = {  
  72.                     type: "boolean",  
  73.                     validation: {  
  74.                         required: true  
  75.                     }  
  76.                 };  
  77.             } else if (propType == "string") {  
  78.                 var parsedDate = kendo.parseDate(gridData[property]);  
  79.                 if (parsedDate) {  
  80.                     fields[property] = {  
  81.                         type: "date",  
  82.                         validation: {  
  83.                             required: true  
  84.                         }  
  85.                     };  
  86.                     dateFields.push(property);  
  87.                 } else {  
  88.                     fields[property] = {  
  89.                         validation: {  
  90.                             required: true  
  91.                         }  
  92.                     };  
  93.                 }  
  94.             } else {  
  95.                 fields[property] = {  
  96.                     validation: {  
  97.                         required: true  
  98.                     }  
  99.                 };  
  100.             }  
  101.   
  102.         }  
  103.         model.fields = fields;  
  104.   
  105.         return model;  
  106.     }  
  107.   
  108.     function OnGridDataBound(e) {  
  109.   
  110.         var grid = $("#grid").data("kendoGrid");  
  111.         var gridData = grid.dataSource.view();  
  112.         for (var i = 0; i < gridData.length; i++) {  
  113.             var currentUid = gridData[i].uid;  
  114.             if (gridData[i].Company == "Company A") {  
  115.                 var currentRow = grid.table.find("tr[data-uid='" + currentUid + "']");  
  116.                 //var createUserButton = $(currentRow).find("butCreateUser");  
  117.                 //createUserButton.hide();  
  118.                 currentRow.css('background-color''lightblue');  
  119.             }  
  120.         }  
  121.     }  
  122. </script>     

From the above databound function in the code, you can observe the following functionalities.

  1. grid.dataSource.view() is used to get the complete dataset of the Kendo Grid.
  2. We are fetching the uid from the Kendo Grid which is the unique id set for all the rows in the Grid.
  3. Based on the company name condition, we are setting the background color for rows.
Result
 
 
From the above image, you can notice the row background color is set only for Company A.
 
This customization will become very handy when we are dealing with custom/command buttons in Kendo Grid, as shown in the below example.
 
CustomRowKendoGrid.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>  Customize Row in Dynamic kendo Grid</h3>  
  19.     <div id="grid" style="width:1000px"></div>  
  20. </body>  
  21.   
  22. </html>  
  23. <script type="text/javascript">  
  24.   
  25.     $(document).ready(function () {  
  26.         $.ajax({  
  27.             url: "/api/Employee/EmployeeList",  
  28.             success:function(result)  
  29.             {  
  30.                 generateGrid(result);  
  31.   
  32.             }  
  33.         })  
  34.   
  35.   
  36.   
  37.     })  
  38.     function generateGrid(gridData) {  
  39.   
  40.         var model = generateModel(gridData[0]);  
  41.         $("#grid").kendoGrid({  
  42.             dataSource: {  
  43.                 data: gridData,  
  44.                  model: model,  
  45.             },  
  46.             dataBound: OnGridDataBound,  
  47.             selectable: true,  
  48.             pageable:{  
  49.                 pageSize:5  
  50.             },  
  51.             sortable: true,  
  52.          columns: ColumnGeneration(gridData),  
  53.         }).data('kendoGrid');  
  54.   
  55.     }  
  56.   
  57.     function generateModel(gridData) {  
  58.         var model = {};  
  59.         model.id = "EmployeeID";  
  60.         var fields = {};  
  61.         for (var property in gridData) {  
  62.             var propType = typeof gridData[property];  
  63.             if (propType == "number") {  
  64.                 fields[property] = {  
  65.                     type: "number",  
  66.                     validation: {  
  67.                         required: true  
  68.                     }  
  69.                 };  
  70.             } else if (propType == "boolean") {  
  71.                 fields[property] = {  
  72.                     type: "boolean",  
  73.                     validation: {  
  74.                         required: true  
  75.                     }  
  76.                 };  
  77.             } else if (propType == "string") {  
  78.                 var parsedDate = kendo.parseDate(gridData[property]);  
  79.                 if (parsedDate) {  
  80.                     fields[property] = {  
  81.                         type: "date",  
  82.                         validation: {  
  83.                             required: true  
  84.                         }  
  85.                     };  
  86.                     dateFields.push(property);  
  87.                 } else {  
  88.                     fields[property] = {  
  89.                         validation: {  
  90.                             required: true  
  91.                         }  
  92.                     };  
  93.                 }  
  94.             } else {  
  95.                 fields[property] = {  
  96.                     validation: {  
  97.                         required: true  
  98.                     }  
  99.                 };  
  100.             }  
  101.   
  102.         }  
  103.         model.fields = fields;  
  104.   
  105.         return model;  
  106.     }  
  107.   
  108.     function ColumnGeneration(gridData)  
  109.     {  
  110.           
  111.         var gridObj = gridData[0];  
  112.         GridTitleArray = [];  
  113.   
  114.         $.each(gridObj, function (gridTitle, element) {  
  115.             GridTitleArray.push(gridTitle)  
  116.         });  
  117.         GridColumnGeneration = [];  
  118.         for(var i=0;i<GridTitleArray.length;i++)  
  119.         {  
  120.               
  121.               
  122.               
  123.                 GridColumnGeneration.push({ title: GridTitleArray[i], field: GridTitleArray[i], lockable: false, width: 200 })  
  124.               
  125.   
  126.   
  127.         }  
  128.   
  129.         GridColumnGeneration.push({ command: ["edit""destroy"], title: " ", width: "250px" })  
  130.   
  131.         return GridColumnGeneration;  
  132.   
  133.     }  
  134.     function OnGridDataBound(e) {  
  135.   
  136.         var grid = $("#grid").data("kendoGrid");  
  137.         var gridData = grid.dataSource.view();  
  138.         for (var i = 0; i < gridData.length; i++) {  
  139.             var currentUid = gridData[i].uid;  
  140.             if (gridData[i].Company == "Company A") {  
  141.                 var currentRow = grid.table.find("tr[data-uid='" + currentUid + "']");  
  142.                   
  143.                 currentRow.css('background-color''lightblue');  
  144.             }  
  145.             if(gridData[i].Company == "Company B")  
  146.             {  
  147.                 var currentRow = grid.table.find("tr[data-uid='" + currentUid + "']");  
  148.                 var createUserButton = $(currentRow).find(".k-grid-edit");  
  149.                 createUserButton.hide();  
  150.   
  151.             }  
  152.         }  
  153.     }  
  154. </script>  
Result
 
From the above image, you can notice that the "Edit" button is hidden for Company B. 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.


Similar Articles