Custom Download In Kendo Grid

In this article you will learn how to perform a custom download in Kendo grid.

Kendo Grid comes with an awesome feature called Export to Excel in build functionality to download the grid details. In this article I’m going to explain how to customize the functionality based on the check box selection in the Kendo Grid.

I am going to use the following API which is used as a source to populate the Grid. Please read my previous article to get an idea about how to create an API using ASP.NET WEB API.

API:

GET: /api/Employees

Response of the above End Point in POSTMAN

                                                                                               

Database Table:

                                                                                              
 

Now the API is ready to consume.

Using a Kendo Grid with MVVM pattern

Creating a HTML page

Create a new HTML page in the project.

Design:

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title></title>  
  5.     <meta charset="utf-8" />  
  6.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.1.226/styles/kendo.common.min.css">  
  7.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.1.226/styles/kendo.default.min.css">  
  8.     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
  9.   
  10.     <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>  
  11.     <script src="http://kendo.cdn.telerik.com/2016.1.226/js/jszip.min.js"></script>  
  12.     <script src="http://kendo.cdn.telerik.com/2016.1.226/js/kendo.all.min.js"></script>  
  13.     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
  14.     <script src="Scripts/ViewModel/Core.js"></script>  
  15.     <script src="Scripts/ViewModel/Data.js"></script>  
  16.     <script src="Scripts/ViewModel/ViewModel.js"></script>  
  17.   
  18. </head>  
  19. <body>  
  20.   
  21.     <div class="col-lg-12">  
  22.         <div id="Main" class="main"></div>  
  23.     </div>  
  24.   
  25.     <script type="text/x-kendo-template" id="Layout-temp">  
  26.         <div class="col-lg-12">  
  27.             <div id="content"></div>  
  28.         </div>  
  29.     </script>  
  30.    
  31.       
  32.     <script type="text/x-kendo-template" id="Dashboard-temp">  
  33.         <div class="row" style="margin-top:20px">  
  34.             <button id="Btn_Download" class="btn btn-default" data-bind="click:DownloadEmp">Download</button>  
  35.             
  36.         </div>  
  37.         <br />  
  38.         <br />  
  39.   
  40.         <div class="row">  
  41.             <div class="row margin-t10">  
  42.                 <div class="col-lg-12" id="scroll">  
  43.                     <div data-role="grid" id="EmployeeGrid"  
  44.                          data-sortable="true"  
  45.                          data-scrollable="true"  
  46.                          data-resizable="true"  
  47.                          data-pageable="{refresh: true, pageSizes: [25, 50, 100, 200]}"  
  48.                          data-row-template="EmployeeGrid_RowTemplate"  
  49.                          data-columns="[  
  50.                           {'width':'30px','headerTemplate':'<input type= \'checkbox\' id=\'HeaderCheckbox\' />' },  
  51.                          { 'field': ' FirstName','width':'100px'},  
  52.                     { 'field': ' LastName','width':'100px'}  
  53.                             
  54.                 ]"  
  55.                 data-bind="source:Gridlist,events:{dataBound: onDataBound}" />  
  56.   
  57.             </div>  
  58.                 </div>  
  59.             </div>  
  60. </script>  
  61.     <script type="text/x-kendo-template" id="EmployeeGrid_RowTemplate">  
  62.         <tr data-uid="#: uid #">  
  63.             <td><input type="checkbox" class="rowcheckbox" name="it" /></td>  
  64.             <td><span>#= FirstName #</span></td>  
  65.   
  66.             <td> <span>#= LastName #</span></td>  
  67.         </tr>  
  68.     </script>  
  69.   
  70.      
  71.   
  72. </body>  
  73. </html>  

Please read my previous article to get an idea about implementing the row template in Kendo Grid

Creating a JavaScript file

View Model:

Create a JavaScript file, in my case I named it ViewModel.js. The View-Model is a representation of your data (the Model) which will be displayed in the View.

ViewModel.Js

  1. (function (G, $, undefined) {  
  2.   
  3.   
  4.     $.extend(true, G, {  
  5.         KendoGrid: {  
  6.             ViewModel: {  
  7.                 DashboardModel: new kendo.observable({  
  8.                     Gridlist: G.KendoGrid.Data.GridList,  
  9.                     
  10.          
  11.                       
  12.                     onDataBound: function (e) {  
  13.                         $('#EmployeeGrid thead').each(function () {  
  14.                             kendo.bind($(this), G.KendoGrid.ViewModel.DashboardModel);  
  15.                         });  
  16.                         $(".rowcheckbox").bind("change"function (e) {  
  17.                             if ($(this).is(':checked')) {  
  18.                                 $(e.target).closest("tr").addClass("select");  
  19.                             } else {  
  20.                                 $(e.target).closest("tr").removeClass("select");  
  21.                             }  
  22.                         });  
  23.                         $("#HeaderCheckbox").on("click"function (e) {  
  24.                             if ($(this).is(':checked')) {  
  25.                                 $('div input').closest("tr").addClass("select");  
  26.                             } else {  
  27.                                 $('div input').closest("tr").removeClass("select");  
  28.                             }  
  29.                         });  
  30.                     },  
  31.                     DownloadEmp:function()  
  32.                     {  
  33.                         var checked = G.KendoGrid.ViewModel.GetCheckedRowIds();  
  34.                           
  35.                         var grid = $("#EmployeeGrid").data("kendoGrid");  
  36.                           
  37.                         if (checked.length == grid.dataSource.total())  
  38.                         {  
  39.                               
  40.                                 alert(checked.length)  
  41.                                 var grid = $("#EmployeeGrid").data("kendoGrid");  
  42.                                 grid.saveAsExcel();  
  43.                               
  44.                         }  
  45.                         else  
  46.                         {  
  47.                               
  48.                        
  49.                             var grid = $("#EmployeeGrid").getKendoGrid();  
  50.                             var rows = [{  
  51.                                 cells: [  
  52.   
  53.                                     
  54.                                   { value: "FirstName" },  
  55.                                   { value: "LastName" },  
  56.                                    
  57.                                 ]  
  58.                             }];  
  59.                             var trs = $("#EmployeeGrid").find('tr');  
  60.                             for (var i = 0; i < trs.length; i++) {  
  61.                                 if ($(trs[i]).find(":checkbox").is(":checked")) {  
  62.                                     var dataItem = grid.dataItem(trs[i]);  
  63.                                     rows.push({  
  64.                                         cells: [  
  65.                                            
  66.                                           { value: dataItem.FirstName },  
  67.                                           { value: dataItem.LastName },  
  68.                                             
  69.                                         ]  
  70.                                     })  
  71.                                 }  
  72.                             }  
  73.                             excelExport(rows)  
  74.                         }  
  75.   
  76.                     },  
  77.                     
  78.                      
  79.                     
  80.                 }),  
  81.                 CreateXlsRow: function (row) {  
  82.                     return {  
  83.                         cells: [  
  84.                             { value: row.FirstName },  
  85.                             { value: row.LastName },  
  86.   
  87.                         ]  
  88.                     };  
  89.                 },  
  90.                 GetCheckedRowIds: function () {  
  91.                     return $.map($('#EmployeeGrid input.rowcheckbox:checked'), function (i) {  
  92.                         return G.KendoGrid.ViewModel.DashboardModel.Gridlist.getByUid($(i).closest("tr").data('uid')).id;  
  93.                     });  
  94.                 },  
  95.             }  
  96.         }  
  97.             });  
  98. })(window.Gni = window.Gni || {}, jQuery);  
  99. function excelExport(rows) {  
  100.   
  101.     var workbook = new kendo.ooxml.Workbook({  
  102.         sheets: [  
  103.           {  
  104.               columns: [  
  105.                 { autoWidth: true },  
  106.                 { autoWidth: true }  
  107.               ],  
  108.               title: "EmployeeInfo",  
  109.               rows: rows  
  110.           }  
  111.         ]  
  112.     });  
  113.     kendo.saveAs({ dataURI: workbook.toDataURL(), fileName: "EmployeeInfo.xlsx" });  
  114. }  
  • DownloadEmp function is responsible to download the grid details based on the checkbox selection.
  • GetcheckedRowIds function is used to get the selected rows details in the grid based on the uid.
  • onDataBound function is used to bind the Models in the Grid. 

Data: Create a JavaScript file, in my case I named it Data.js, This script is responsible to bind the DataSource by requesting the API.

Data.js

  1. (function (G, $, K, undefined) {  
  2.   
  3.     $.extend(true, G, {  
  4.         KendoGrid: {  
  5.             Data: {  
  6.                 GridList: new K.data.DataSource({  
  7.                     //navigatable: true,  
  8.                     batch: true,  
  9.                     pageSize: 5,  
  10.                     transport: {  
  11.                         read: {  
  12.                             url: 'api/Employees',  
  13.                             type: 'GET',  
  14.                             dataType: 'json',  
  15.                             
  16.                         },  
  17.                         parameterMap: function (data, operation) {  
  18.                             if (operation == "read") {  
  19.                                 console.log(JSON.stringify(data))  
  20.                                 return JSON.stringify(data);  
  21.                             }  
  22.                             return data;  
  23.                         }  
  24.                     },  
  25.                     schema: {  
  26.                         
  27.                         model: {  
  28.                             id: "EmployeeID",  
  29.                             fields: {  
  30.                                 "FirstName": { type: "string"},  
  31.                                 "LastName": { type: "string"},  
  32.                                  
  33.                             }  
  34.                         }  
  35.                     },  
  36.                       
  37.                      
  38.                 }),  
  39.                 
  40.             }  
  41.         }  
  42.     });  
  43. })(window.Gni = window.Gni || {}, jQuery, kendo);  

Core:

Create a JavaScript file, in my case I named it Core.js. This core script is used to start the rendering of the templates and calls the view model to bind the data in the UI.

Core.js

  1.    $.extend(true, G, {  
  2.         KendoGrid: {  
  3.             Core: {  
  4.                 ActiveEvents:function()  
  5.                 {  
  6.   
  7.                     $('#HeaderCheckbox').on('click'function () {  
  8.                         var checked = $(this).is(':checked');  
  9.                         $('#EmployeeGrid input.rowcheckbox').prop('checked', checked);  
  10.                     });  
  11.                 },  
  12.                  
  13.                  
  14.             }  
  15.         }  
  16.     });  
  17. })(window.Gni = window.Gni || {}, jQuery);  
  18. $(function () {  
  19.         var Layout = new kendo.Layout("Layout-temp");  
  20.         var DashboardView = new kendo.View("Dashboard-temp", { model: Gni.KendoGrid.ViewModel.DashboardModel });  
  21.         var router = new kendo.Router({  
  22.             init: function () {  
  23.                 Layout.render("#Main");  
  24.                 Layout.showIn("#content", DashboardView);  
  25.        
  26.             }  
  27.         });  
  28.         router.start();  
  29.         Gni.KendoGrid.Core.ActiveEvents();  
  30.      
  31.     });  

The ActiveEvents function is used to define the Header checkbox; i.e, according to the header checkbox status the checkbox in each row of the grid should change their status.

Result in Browser:

Downloading entire records in grid
 
 
 
 Downloading Particular selected record
 
 
 

I hope you have enjoyed this article. Your valuable feedback, question, or comments about this article are always welcomed.

Read more articles on jQuery: