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.
- Creating an ASP.NET Web API application
- Creating a Controller
- Testing the REST API
- Constructing a Kendo Grid with the dynamic column
- 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
- public class Employee
- {
- public Employee(int Id, string Name, string Designation,string Company)
- {
- this.EmployeeID = Id;
- this.EmployeeName = Name;
- this.Designation = Designation;
- this.Company = Company;
-
- }
- public int EmployeeID { get; set; }
- public string EmployeeName { get; set; }
- public string Designation { get; set; }
- public string Company { get; set; }
- }
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
- [RoutePrefix("api/Employee")]
- public class EmployeeController : ApiController
- {
- [HttpGet]
- [AllowAnonymous]
- [Route("EmployeeList")]
- public HttpResponseMessage GetEmployee()
- {
- try
- {
- List<Employee> EmpLists = new List<Employee>();
- EmpLists.Add(new Employee(1, "Govind Raj", "Business Analyst","Company A"));
- EmpLists.Add(new Employee(2, "Krishn Mahato", "Development","Company B"));
- EmpLists.Add(new Employee(3, "Bob Ross", "Testing","Company A"));
- EmpLists.Add(new Employee(4, "Steve Davis", "Development","Company A"));
- EmpLists.Add(new Employee(5, "Dave Tucker", "Infrastructure","Company B"));
- EmpLists.Add(new Employee(6, "James Anderson", "HR","Company A"));
- return Request.CreateResponse(HttpStatusCode.OK, EmpLists, Configuration.Formatters.JsonFormatter);
- }
- catch (Exception ex)
- {
- return Request.CreateResponse(HttpStatusCode.OK, ex.Message, Configuration.Formatters.JsonFormatter);
- }
- }
- }
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
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>Untitled</title>
-
- <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1118/styles/kendo.common.min.css">
- <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1118/styles/kendo.rtl.min.css">
- <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1118/styles/kendo.default.min.css">
- <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1118/styles/kendo.mobile.all.min.css">
-
- <script src="http://code.jquery.com/jquery-1.12.3.min.js"></script>
- <script src="http://kendo.cdn.telerik.com/2016.3.1118/js/angular.min.js"></script>
- <script src="http://kendo.cdn.telerik.com/2016.3.1118/js/jszip.min.js"></script>
- <script src="http://kendo.cdn.telerik.com/2016.3.1118/js/kendo.all.min.js"></script>
- </head>
- <body>
- <h3> Dynamic Column Binding in the kendo Grid</h3>
- <div id="grid" style="width:600px;"></div>
- </body>
-
- </html>
- <script type="text/javascript">
-
- var dateFields=[];
- $(document).ready(function () {
- $.ajax({
- url: "/api/Employee/EmployeeList",
- success:function(result)
- {
- generateGrid(result);
-
- },
- error:function()
- {
- alert("Some error has occurred");
- }
- })
-
-
- })
- function generateGrid(gridData) {
- debugger;
- var model = generateModel(gridData[0]);
- var grid = $("#grid").kendoGrid({
- dataSource: {
- data: gridData,
- model: model,
- },
- editable: true,
- sortable: true,
-
- });
-
- }
-
- function generateModel(gridData) {
- var model = {};
- model.id = "EmployeeID";
- var fields = {};
- for (var property in gridData) {
- var propType = typeof gridData[property];
- if (propType == "number") {
- fields[property] = {
- type: "number",
- validation: {
- required: true
- }
- };
- } else if (propType == "boolean") {
- fields[property] = {
- type: "boolean",
- validation: {
- required: true
- }
- };
- } else if (propType == "string") {
- var parsedDate = kendo.parseDate(gridData[property]);
- if (parsedDate) {
- fields[property] = {
- type: "date",
- validation: {
- required: true
- }
- };
- dateFields.push(property);
- } else {
- fields[property] = {
- validation: {
- required: true
- }
- };
- }
- } else {
- fields[property] = {
- validation: {
- required: true
- }
- };
- }
-
- }
- model.fields = fields;
-
- return model;
- }
-
- </script>
From the code mentioned above, you can observe the following functionalities to construct the dynamic Grid.
- 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.
- generateGrid function is used to construct the Grid, which is based on the response from the Service.
- 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
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>Untitled</title>
-
- <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1118/styles/kendo.common.min.css">
- <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1118/styles/kendo.rtl.min.css">
- <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1118/styles/kendo.default.min.css">
- <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1118/styles/kendo.mobile.all.min.css">
-
- <script src="http://code.jquery.com/jquery-1.12.3.min.js"></script>
- <script src="http://kendo.cdn.telerik.com/2016.3.1118/js/angular.min.js"></script>
- <script src="http://kendo.cdn.telerik.com/2016.3.1118/js/jszip.min.js"></script>
- <script src="http://kendo.cdn.telerik.com/2016.3.1118/js/kendo.all.min.js"></script>
- </head>
- <body>
- <h3> Customize Row in Dynamic kendo Grid</h3>
- <div id="grid" style="width:600px;"></div>
- </body>
-
- </html>
- <script type="text/javascript">
-
- var dateFields=[];
- $(document).ready(function () {
- $.ajax({
- url: "/api/Employee/EmployeeList",
- success:function(result)
- {
- generateGrid(result);
-
- },
- error:function()
- {
- alert("Some error has occurred");
- }
- })
-
-
- })
- function generateGrid(gridData) {
- debugger;
- var model = generateModel(gridData[0]);
- var grid = $("#grid").kendoGrid({
- dataSource: {
- data: gridData,
- model: model,
- },
- editable: true,
- sortable: true,
- dataBound: OnGridDataBound,
- });
-
- }
-
- function generateModel(gridData) {
- var model = {};
- model.id = "EmployeeID";
- var fields = {};
- for (var property in gridData) {
- var propType = typeof gridData[property];
- if (propType == "number") {
- fields[property] = {
- type: "number",
- validation: {
- required: true
- }
- };
- } else if (propType == "boolean") {
- fields[property] = {
- type: "boolean",
- validation: {
- required: true
- }
- };
- } else if (propType == "string") {
- var parsedDate = kendo.parseDate(gridData[property]);
- if (parsedDate) {
- fields[property] = {
- type: "date",
- validation: {
- required: true
- }
- };
- dateFields.push(property);
- } else {
- fields[property] = {
- validation: {
- required: true
- }
- };
- }
- } else {
- fields[property] = {
- validation: {
- required: true
- }
- };
- }
-
- }
- model.fields = fields;
-
- return model;
- }
-
- function OnGridDataBound(e) {
-
- var grid = $("#grid").data("kendoGrid");
- var gridData = grid.dataSource.view();
- for (var i = 0; i < gridData.length; i++) {
- var currentUid = gridData[i].uid;
- if (gridData[i].Company == "Company A") {
- var currentRow = grid.table.find("tr[data-uid='" + currentUid + "']");
-
-
- currentRow.css('background-color', 'lightblue');
- }
- }
- }
- </script>
From the above databound function in the code, you can observe the following functionalities.
- grid.dataSource.view() is used to get the complete dataset of the Kendo Grid.
- We are fetching the uid from the Kendo Grid which is the unique id set for all the rows in the Grid.
- 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
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>Untitled</title>
-
- <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1118/styles/kendo.common.min.css">
- <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1118/styles/kendo.rtl.min.css">
- <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1118/styles/kendo.default.min.css">
- <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1118/styles/kendo.mobile.all.min.css">
-
- <script src="http://code.jquery.com/jquery-1.12.3.min.js"></script>
- <script src="http://kendo.cdn.telerik.com/2016.3.1118/js/angular.min.js"></script>
- <script src="http://kendo.cdn.telerik.com/2016.3.1118/js/jszip.min.js"></script>
- <script src="http://kendo.cdn.telerik.com/2016.3.1118/js/kendo.all.min.js"></script>
- </head>
- <body>
- <h3> Customize Row in Dynamic kendo Grid</h3>
- <div id="grid" style="width:1000px"></div>
- </body>
-
- </html>
- <script type="text/javascript">
-
- $(document).ready(function () {
- $.ajax({
- url: "/api/Employee/EmployeeList",
- success:function(result)
- {
- generateGrid(result);
-
- }
- })
-
-
-
- })
- function generateGrid(gridData) {
-
- var model = generateModel(gridData[0]);
- $("#grid").kendoGrid({
- dataSource: {
- data: gridData,
- model: model,
- },
- dataBound: OnGridDataBound,
- selectable: true,
- pageable:{
- pageSize:5
- },
- sortable: true,
- columns: ColumnGeneration(gridData),
- }).data('kendoGrid');
-
- }
-
- function generateModel(gridData) {
- var model = {};
- model.id = "EmployeeID";
- var fields = {};
- for (var property in gridData) {
- var propType = typeof gridData[property];
- if (propType == "number") {
- fields[property] = {
- type: "number",
- validation: {
- required: true
- }
- };
- } else if (propType == "boolean") {
- fields[property] = {
- type: "boolean",
- validation: {
- required: true
- }
- };
- } else if (propType == "string") {
- var parsedDate = kendo.parseDate(gridData[property]);
- if (parsedDate) {
- fields[property] = {
- type: "date",
- validation: {
- required: true
- }
- };
- dateFields.push(property);
- } else {
- fields[property] = {
- validation: {
- required: true
- }
- };
- }
- } else {
- fields[property] = {
- validation: {
- required: true
- }
- };
- }
-
- }
- model.fields = fields;
-
- return model;
- }
-
- function ColumnGeneration(gridData)
- {
-
- var gridObj = gridData[0];
- GridTitleArray = [];
-
- $.each(gridObj, function (gridTitle, element) {
- GridTitleArray.push(gridTitle)
- });
- GridColumnGeneration = [];
- for(var i=0;i<GridTitleArray.length;i++)
- {
-
-
-
- GridColumnGeneration.push({ title: GridTitleArray[i], field: GridTitleArray[i], lockable: false, width: 200 })
-
-
-
- }
-
- GridColumnGeneration.push({ command: ["edit", "destroy"], title: " ", width: "250px" })
-
- return GridColumnGeneration;
-
- }
- function OnGridDataBound(e) {
-
- var grid = $("#grid").data("kendoGrid");
- var gridData = grid.dataSource.view();
- for (var i = 0; i < gridData.length; i++) {
- var currentUid = gridData[i].uid;
- if (gridData[i].Company == "Company A") {
- var currentRow = grid.table.find("tr[data-uid='" + currentUid + "']");
-
- currentRow.css('background-color', 'lightblue');
- }
- if(gridData[i].Company == "Company B")
- {
- var currentRow = grid.table.find("tr[data-uid='" + currentUid + "']");
- var createUserButton = $(currentRow).find(".k-grid-edit");
- createUserButton.hide();
-
- }
- }
- }
- </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.