Persist The State Of The Kendo Grid Using Local Storage

Introduction

This article tells about how to maintain the complete state of Kendo Grid, using local storage. The Application is developed, using Entity Framework database first approach and ASP.NET MVC.

Prerequisites

Basic knowledge in ASP.NET MVC, Entity Framework and Kendo UI Framework.

Persist State in Kendo Grid 

Please go through my previous articles, as mentioned below before proceeding-

My database schema is shown in the figure, given below-


EmployeesCRUDController.cs 
  1. public class EmployeesCRUDController : Controller  
  2.     {  
  3.         private EmployeeEntities db = new EmployeeEntities();  
  4.   
  5.         // GET: EmployeesCRUD  
  6.         public ActionResult Index()  
  7.         {  
  8.             return View();  
  9.         }  
  10.   
  11.         public ActionResult GetAllEmployee([DataSourceRequest]DataSourceRequest request)  
  12.         {  
  13.             try  
  14.             {  
  15.   
  16.                 var employee = db.Employees.ToList();  
  17.   
  18.                 return Json(employee.ToDataSourceResult(request),JsonRequestBehavior.AllowGet);  
  19.             }  
  20.             catch (Exception ex)  
  21.             {  
  22.                 return Json(ex.Message);  
  23.             }  
  24.   
  25.         }  
  26.   
  27.         public ActionResult UpdateEmployee([DataSourceRequest]DataSourceRequest request, Employee emp)  
  28.         {  
  29.             try  
  30.             {  
  31.                 if (ModelState.IsValid)  
  32.                 {  
  33.                     db.Entry(emp).State = EntityState.Modified;  
  34.                     db.SaveChanges();  
  35.                     return Json(new[] { emp }.ToDataSourceResult(request, ModelState),JsonRequestBehavior.AllowGet);  
  36.   
  37.                 }  
  38.                 else  
  39.                 {  
  40.                     return Json(db.Employees.ToList(),JsonRequestBehavior.AllowGet);  
  41.                 }  
  42.             }  
  43.             catch (Exception ex)  
  44.             {  
  45.                 return Json(ex.Message);  
  46.             }  
  47.         }  
  48.   
  49.         public ActionResult AddEmployee([DataSourceRequest]DataSourceRequest request, Employee emp)  
  50.         {  
  51.             try  
  52.             {  
  53.                 if (ModelState.IsValid)  
  54.                 {  
  55.   
  56.                     db.Employees.Add(emp);  
  57.                     db.SaveChanges();  
  58.                     var _emplist = db.Employees.ToList();  
  59.                     return Json(new[] { emp }.ToDataSourceResult(request, ModelState),JsonRequestBehavior.AllowGet);  
  60.                 }  
  61.   
  62.                 else  
  63.                 {  
  64.                     return Json(db.Employees.ToList(),JsonRequestBehavior.AllowGet);  
  65.                 }  
  66.             }  
  67.             catch (Exception ex)  
  68.             {  
  69.                 return Json(ex.Message);  
  70.             }  
  71.         }  
  72.   
  73.         public ActionResult DeleteEmployee([DataSourceRequest]DataSourceRequest request, Employee emp)  
  74.         {  
  75.             try  
  76.             {  
  77.                 Employee employee = db.Employees.Find(emp.EmployeeID);  
  78.                 if (employee == null)  
  79.                 {  
  80.                     return Json("Employee Not Found");  
  81.                 }  
  82.   
  83.                 db.Employees.Remove(employee);  
  84.                 db.SaveChanges();  
  85.                 return Json(db.Employees.ToList(),JsonRequestBehavior.AllowGet);  
  86.             }  
  87.             catch (Exception ex)  
  88.             {  
  89.                 return Json(ex.Message);  
  90.             }  
  91.         }  
  92.     }   

Index.cshtml

  1. @model KendoMvcApp.Models.Employee  
  2.   
  3. @{  
  4.     ViewBag.Title = "Kendo CRUD";  
  5.   
  6. }  
  7.   
  8. <h2>Kendo CRUD</h2>  
  9.   
  10. <div class="container">  
  11.     <div class="row">  
  12.   
  13.         @(Html.Kendo().Grid<KendoMvcApp.Models.Employee>()  
  14.     .Name("EmpGrid")  
  15.     .Selectable()  
  16.     .Columns(columns =>  
  17.     {  
  18.         //  columns.Bound(c => c.EmployeeID);  
  19.         columns.Bound(c => c.FirstName);  
  20.         columns.Bound(c => c.LastName);  
  21.         columns.Command(command =>  
  22.         {  
  23.             command.Edit();  
  24.             command.Destroy();  
  25.         }).Width(200);  
  26.   
  27.     })  
  28.     .DataSource(dataSource => dataSource  
  29.         .Ajax()  
  30.         .Model(model =>  
  31.         {  
  32.             model.Id(emp => emp.EmployeeID);  
  33.             model.Field(emp => emp.EmployeeID).Editable(false);  
  34.         }  
  35.         )  
  36.         .Read(read => read.Action("GetAllEmployee""EmployeesCRUD"))  
  37.       .Update(update => update.Action("UpdateEmployee""EmployeesCRUD"))  
  38.       .Create(create => create.Action("AddEmployee""EmployeesCRUD"))  
  39.       .Destroy(destroy => destroy.Action("DeleteEmployee""EmployeesCRUD"))  
  40.   
  41.         )  
  42.         .Events(e =>e.DataBound("grid_dataBound"))  
  43.         .Filterable()  
  44.    .ToolBar(toolbar => toolbar.Create())  
  45.   
  46.    // Set grid editable.  
  47.    .Editable(editable => editable.Mode(GridEditMode.InLine))  
  48.   
  49.     // Set grid sortable.  
  50.     .Sortable()  
  51.   
  52.     // Set grid selectable.  
  53.     .Selectable()  
  54.   
  55.     // Set grid pagable.  
  56.     .Pageable(pageable =>  
  57.     {  
  58.         pageable.Refresh(true);  
  59.         pageable.PageSizes(true);  
  60.     })  
  61.         )  
  62.     </div>  
  63. </div>  
  64. <div>  
  65.     <script type="text/javascript">  
  66.         $(document).ready(function () {  
  67.             var grid = $("#EmpGrid").data("kendoGrid");  
  68.             var options = localStorage["kendo-grid-options"];  
  69.             if (options) {  
  70.                 grid.setOptions(JSON.parse(options));  
  71.             }  
  72.         });  
  73.   
  74.         function grid_dataBound() {  
  75.             var grid = $("#EmpGrid").data("kendoGrid");  
  76.             localStorage["kendo-grid-options"] = kendo.stringify(grid.getOptions());  
  77.         }  
  78.         
  79.     </script>  
  80. </div>   

I have discussed about the controller, shown above and view in the article CRUD in Kendo Grid using ASP.NET MVC and Entity Framework to perform a CRUD operation in Kendo Grid. Here, I’m going to use the same controller and view to explain how to persist the state of Kendo Grid .

From the view, stated above, you can notice I have added a databound event in Kendo Grid and its respective function definition, which is written in JavaScript, the databound event is fired when Kendo Grid is bound to the data from its data source

When the page loads, we are going to check whether there is any local storage or not. If the local storage [“kenod-grid-options”] exists, we are going to load it as a datasource for Kendo Grid, using the setOptions function.

Please click here to read more about local storage.

When the databound event in Kendo Grid is fired, we are going to get the state of the Grid, using the getoption method and save it as a local storage, which is used to maintain the state of the Grid 

setOption

This function in Kendo Grid is used to enable/disable a particular feature like paging, sorting, filtering or to load the complete state to obtain previously with the getoptions method.

getOption

Retrieves the options, which are currently enabled or disabled on the Grid. It also gives the current state of the dataSource. Now, let us test whether the state of Kendo Grid is maintained or not?

Kendo Grid in Browser

 
From the image, shown above, it is clear that the local storage is created and the complete state of Kendo Grid is saved in it, when the page loads.
 
Sorting State 


After page load


You must have noticed the sorting state in Kendo Grid is maintained after the page loads.

Filtering State

 
After page load
 
 
It is clear from the image, shown above, the filter option as well as previous state sort option is maintained after the page loads.
 
Reference
 
http://docs.telerik.com/kendo-ui/api/javascript/ui/grid  
 
 
Conclusion
 
Thus, the state of Kendo Grid can be maintained completely with the help of the getOption and setOption functions, which is proved from the scenario, shown above, which we worked on. 
 
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