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.
- Creating an ASP.NET Web API Application.
- Creating a Controller.
- Testing the REST API.
- 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.
- public class Employee
- {
- public Employee(int Id, string Name, string Designation)
- {
- this.EmployeeID = Id;
- this.EmployeeName = Name;
- this.Designation = Designation;
-
- }
- public int EmployeeID { get; set; }
- public string EmployeeName { get; set; }
- public string Designation { get; set; }
- }
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
- 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"));
- EmpLists.Add(new Employee(2, "Krishn Mahato", "Development"));
- EmpLists.Add(new Employee(3, "Bob Ross", "Testing"));
- EmpLists.Add(new Employee(4, "Steve Davis", "Development"));
- EmpLists.Add(new Employee(5, "Dave Tucker", "Infrastructure"));
- EmpLists.Add(new Employee(6, "James Anderson", "HR"));
- 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 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
- <!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 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
Figure 5
Let us now deal with the column generation in Kendo Grid. Write the code, mentioned below in DynamicKendoGrid.html
- function ColumnGeneration(gridData)
- {
- var gridObj = gridData[0];
- GridTitleArray = [];
- debugger;
- $.each(gridObj, function (gridTitle, element) {
- GridTitleArray.push(gridTitle)
- });
- GridColumnGeneration = [];
- for(var i=0;i<GridTitleArray.length;i++)
- {
- debugger;
- if (GridTitleArray[i] == 'EmployeeName')
- {
- GridColumnGeneration.push({ title: GridTitleArray[i], field: GridTitleArray[i], template: '<a onclick="rowFunction()" href="\\#">#=EmployeeName#</a>' })
- }
- else{
- GridColumnGeneration.push({ title: GridTitleArray[i], field: GridTitleArray[i] })
- }
-
- }
- return GridColumnGeneration;
- }
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.
- <!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) {
-
- var model = generateModel(gridData[0]);
- $("#grid").kendoGrid({
- dataSource: {
- data: gridData,
- model: model,
- },
- 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++)
- {
-
- if (GridTitleArray[i] == 'EmployeeName')
- {
- GridColumnGeneration.push({ title: GridTitleArray[i], field: GridTitleArray[i], template: '<a onclick="rowFunction()" href="\\#">#=EmployeeName#</a>' })
- }
- else{
- GridColumnGeneration.push({ title: GridTitleArray[i], field: GridTitleArray[i] })
- }
-
- }
- return GridColumnGeneration;
-
- }
- function rowFunction()
- {
- alert("hello!!")
- }
- </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.