The Select All Check Box Header Template In Kendo Grid Using ASP.NET WEB API And Entity Framework

Introduction

This article explains how to implement the select all header check box template in Kendo Grid, using ASP.NET Web API. To explain it, I have created a RESTful GET Service, which is used to load the Data Source of Kendo Grid

Requirements

  • VS 2010 and above
  • SQL Server 2008 and above

Prerequisites

Basic knowledge of ASP.NET WebAPI, jQuery, Kendo UI.

This article flows, as per the following.

  1. Set up the table.
  2. Creating an ASP.NET Web API Application.
  3. Creating a Controller.
  4. Testing the REST API.
  5. Creating a HTML page and implementing select all header check box template in Kendo Grid.

Set up the table

For this article, I have created one table named EmployeeList, the design of which is shown below.

 
Figure 1 

Employee List Table

 
Figure 2 

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 “KGridTemplate"

Figure 3 

Figure 4 

Creating model classes

Now, we will create Entity Framework models from the database tables.

Step 1

Right-click the Models folder, select Add -> ADO.NET Entity Data Model or select Add->New Item. In the Add New Item Window, select data in the left pane and ADO.NET Entity Data Model from the center pane. Name the new model file (In my case, I made it as Employee) and click Add.

Step 2

In the Entity Data Model wizard, select "EF Designer" from the database and click Next.

Figure 5

Step 3

Click New Connection button. The Connection Properties Window will open.
Figure 6

Step 4

In Connection Properties Window, provide the name of the local Server, where the database was created (in this case, (DESKTOP-585QGBN)). After providing the Server name, select Employee from the available databases and click OK.

 
Figure 7

Step 5

You can use the default name for the connection to save Web.Config file. Now, click Next.

Figure 8

Step 6 

Select the table to generate the models for EmployeeList table and click Finish. 

Figure 9

My database schema is shown in the figure given below.

 
Figure 10 

Creating a Controller

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

Write the code given below in EmployeeController.cs

EmployeeController.cs 
  1. [RoutePrefix("api/Employee")]  
  2.   public class EmployeeController : ApiController  
  3.   {  
  4.       EmployeeEntities db = new EmployeeEntities();  
  5.       [HttpGet]  
  6.       [AllowAnonymous]  
  7.       [Route("EmployeeList")]  
  8.       public HttpResponseMessage GetEmployeeList()  
  9.       {  
  10.           try  
  11.           {   
  12.           return Request.CreateResponse(HttpStatusCode.OK, db.EmployeeLists, Configuration.Formatters.JsonFormatter);  
  13.           }  
  14.           catch(Exception ex)  
  15.           {  
  16.               return Request.CreateResponse(HttpStatusCode.OK, ex.Message, Configuration.Formatters.JsonFormatter);  
  17.           }  
  18.   
  19.       }  
  20.   }   

Testing API in Postman

  • API End Point /API/ Employee/ EmployeeList.
  • Type GET.
Figure 11 

Now, our API is ready. Let's create a Kendo Grid Data Source, using the API.

Creating HTML page

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

Remote Data Source in KendoGrid

Click here to learn more about remote Data Source in Kendo Grid
 
kendoGrid.html 
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title>Kendo Grid</title>  
  5.     <meta charset="utf-8" />  
  6.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.common.min.css" />  
  7.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.rtl.min.css" />  
  8.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.silver.min.css" />  
  9.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.mobile.all.min.css" />  
  10.   
  11.     <script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>  
  12.     <script src="http://kendo.cdn.telerik.com/2017.1.118/js/kendo.all.min.js"></script>  
  13. </head>  
  14. <body>  
  15.     <div id="example">  
  16.         <div id="grid"></div>  
  17.         <br />  
  18.         <br />  
  19.         <button id="showSelection" class="k-button">Get Employee Name</button>  
  20.         <script>  
  21.             $(document).ready(function() {  
  22.             var employeeGrid=    $("#grid").kendoGrid({  
  23.                     dataSource: {  
  24.                         type: "json",  
  25.                         transport: {  
  26.                             read: "/api/Employee/EmployeeList"  
  27.                         },  
  28.                         // group:{field:"Company",aggregates:[{field:"Company",aggregate:"count"}]},  
  29.                         schema: {  
  30.                             model: {  
  31.                                 fields: {  
  32.                                     EmployeeID: { type: "number" },  
  33.                                     FirstName: { type: "string" },  
  34.                                     LastName: { type: "string" },  
  35.                                     Company:{type:"string"}  
  36.                                 }  
  37.                             }  
  38.                         },  
  39.                     },  
  40.                         
  41.                     filterable: true,  
  42.                     sortable: true,  
  43.                     dataBound:onDataBound,  
  44.                     pageable: true,  
  45.                     columns: [  
  46.                         {  
  47.                               
  48.                             headerTemplate: `<input type="checkbox" id="headerchb" class="k-checkbox"><label class="k-checkbox-label" for="headerchb"></label>`,  
  49.                             template: function(dataItem){  
  50.                                 return `<input type="checkbox" id="${dataItem.EmployeeID}" class="k-checkbox"><label class="k-checkbox-label" for="${dataItem.EmployeeID}"></label>`  
  51.                             },  
  52.                             width: 50  
  53.                             },  
  54.                 {  
  55.                                 field:"EmployeeID",  
  56.                                 filterable: false  
  57.                             },  
  58.                               
  59.                             {  
  60.                                 field: "FirstName",  
  61.                                 title: " First Name",  
  62.                               
  63.                             }, {  
  64.                                 field: "LastName",  
  65.                                 title: "Last Name"  
  66.                             }, {  
  67.                                 field: "Company",  
  68.                                 title: "Company",  
  69.                   
  70.                             },  
  71.                             
  72.                         ]  
  73.             }).data("kendoGrid");  
  74.               
  75.             employeeGrid.table.on("click"".k-checkbox" , selectRow);  
  76.             $('#headerchb').change(function (ev) {  
  77.                 debugger;  
  78.                 var checked = ev.target.checked;  
  79.                 $('.k-checkbox').each(function(idx, item){  
  80.                     if(checked){  
  81.                         if(!($(item).closest('tr').is('.k-state-selected'))){  
  82.                             $(item).click();  
  83.                         }  
  84.                     } else {  
  85.                         checkedIds={}  
  86.                         if($(item).closest('tr').is('.k-state-selected')){  
  87.                             $(item).click();  
  88.                         }  
  89.                     }  
  90.                 });  
  91.   
  92.             });  
  93.   
  94.             $("#showSelection").bind("click"function () {  
  95.                 var checked = [];  
  96.                 for(var i in checkedIds){  
  97.                     if(checkedIds[i]){  
  98.                         checked.push(i);  
  99.                     }  
  100.                 }  
  101.   
  102.                 alert(checked);  
  103.             });  
  104.             });  
  105.   
  106.           
  107.             var checkedIds = {}  
  108.         //on click of the checkbox:  
  109.             function selectRow() {  
  110.                 debugger;  
  111.             var checked = this.checked,  
  112.                 row = $(this).closest("tr"),  
  113.                 grid = $("#grid").data("kendoGrid"),  
  114.                 dataItem = grid.dataItem(row);  
  115.   
  116.             checkedIds[dataItem.FirstName] = checked;  
  117.               
  118.             if (checked) {  
  119.                 //-select the row  
  120.                 row.addClass("k-state-selected");  
  121.             } else {  
  122.                 //-remove selection  
  123.                 row.removeClass("k-state-selected");  
  124.             }  
  125.               
  126.         }  
  127.   
  128.         //on dataBound event restore previous selected rows:  
  129.         function onDataBound(e) {  
  130.             var view = this.dataSource.view();  
  131.             for(var i = 0; i < view.length;i++){  
  132.                 if(checkedIds[view[i].EmployeeID]){  
  133.                     this.tbody.find("tr[data-uid='" + view[i].uid + "']")  
  134.                       .addClass("k-state-selected")  
  135.                       .find(".checkbox")  
  136.                       .attr("checked","checked");  
  137.                 }  
  138.             }  
  139.         }  
  140.                  
  141.         </script>  
  142.     </div>  
  143. </body>  
  144. </html>  
From the above code, the table on click event is fired when the header check box status changes, the selectrow() function is fired when the check box template status changes. 
 
We have placed one button, which is used to get the name of the employee, which is selected through the check box template.  
 
Result in Browser

 
Figure 12
 
Click the button to get checked employee FirstName.
 
 
Figure 13
 
Header checkbox selection with filtering.
 
Filter the company field by company A
 
 
Figure 14
 
 
Figure 15
 
I hope, you enjoyed this article. Your valuable feedback, questions or comments about this article are always welcome.

Up Next
    Ebook Download
    View all
    Learn
    View all