Search results

State Persistence in ASP.NET MVC Grid control

20 Jan 2022 / 3 minutes to read

State persistence refers to the Grid’s state maintained in the browser’s localStorage even if the browser is refreshed or if you move to the next page within the browser. State persistence stores grid’s model object in the local storage when the EnablePersistence is defined as true.

Maintaining custom query in a persistent state

The grid does not maintain the query params after page load event when the EnablePersistence is set to true. This is because the grid refreshes its query params for every page load. You can maintain the custom query params by resetting the addParams method in the ActionBegin event.

razor
state-persist.cs
Copied to clipboard
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowFiltering(true).EnablePersistence(true).ActionBegin("actionBegin").Columns(col =>
{

    col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("CustomerID").HeaderText("Customer Name").Width("170").Add();
    col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();

}).AllowPaging().PageSettings(page => page.PageCount(5)).Render()

    <script>
    function actionBegin(args) {
        this.query.addParams('$filter', 'EmployeeID eq 1');
    }
    </script>
Copied to clipboard
public IActionResult Index()
 {
    var orders = OrderDetails.GetAllRecords();
    ViewBag.datasource = orders;            
    return View();
 }

Get or set localStorage value

If the EnablePersistence property is set to true, the grid property value is saved in the window.localStorage for reference. You can get/set the localStorage value by using the getItem/setItem method in the window.localStorage.

Copied to clipboard
//get the Grid model.
var value = window.localStorage.getItem('gridGrid'); //"gridGrid" is component name + component id.
var model= JSON.parse(model);
Copied to clipboard
//set the Grid model.
window.localStorage.setItem('gridGrid', JSON.stringify(model)); //"gridGrid" is component name + component id.

Restore initial Grid state

When the EnablePersistence property is set to true, the Grid will keep its state even if the page is reloaded. In some cases, you may be required to retain the Grid in its initial state. The Grid will not retain its initial state now since the EnablePersistence property has been enabled.

You can achieve this by destroying the grid after disabling the EnablePersistence property and clearing the local storage data, as shown in the sample below.

razor
initial-grid.cs
Copied to clipboard
@Html.EJS().Button("restore").Content("Restore to initial state").IsPrimary(true).Render()

@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowFiltering(true).EnablePersistence(true).Columns(col =>
{

    col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("CustomerID").HeaderText("Customer Name").Width("170").Add();
    col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();

}).AllowPaging(true).PageSettings(page => page.PageCount(5)).Render()

<script>
    document.getElementById('restore').onclick = function () {
        document.getElementById('Grid').ej2_instances[0].enablePersistence = false;
        window.localStorage.setItem("gridGrid", "");
        document.getElementById('Grid').ej2_instances[0].destroy();
        //reloads the page
        location.reload();
    }
</script>
Copied to clipboard
public IActionResult Index()
 {
    var orders = OrderDetails.GetAllRecords();
    ViewBag.datasource = orders;            
    return View();
 }

How to add a new column while using enablePersistence

The Grid columns can be persisted when the enablePersistence property is set to true. If you want to add the new columns with the existing persist state, you can use the Grid inbuilt method such as column.push and call the refreshColumns() method for UI changes. Please refer to the following sample for more information.

razor
column-add.cs
Copied to clipboard
@Html.EJS().Button("add").Content("Add Columns").IsPrimary(true).Render()

@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).EnablePersistence(true).Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("CustomerID").HeaderText("Customer Name").Width("170").Add();
    col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();

}).AllowPaging(true).PageSettings(page => page.PageCount(5)).Render()

<script>
    document.getElementById('add').onclick = function () {
        var obj = { field: "Freight", headerText: 'Freight', width: 120 }
        document.getElementById('Grid').ej2_instances[0].columns.push(obj); //you can add the columns by using the Grid columns method
        document.getElementById('Grid').ej2_instances[0].refreshColumns();
    }
</script>
Copied to clipboard
public IActionResult Index()
 {
    var orders = OrderDetails.GetAllRecords();
    ViewBag.Datasource = orders;            
    return View();
 }

How to prevent columns from persisting

When the EnablePersistence property is set to true, the Grid properties such as Grouping, Paging, Filtering, Sorting, and Columns will persist. You can use the addOnPersist method to prevent these Grid properties from persisting.

The following example demonstrates how to prevent Grid columns from persisting. In the DataBound event of the Grid, you can override the addOnPersist method and remove the columns from the key list given for persistence.

Note: When the EnablePersistence property is set to true, the Grid properties such as column template, column formatter, header text, and value accessor will not persist.

razor
column-prevent.cs
Copied to clipboard
@Html.EJS().Button("add").Content("Add Columns").IsPrimary(true).Render()
@Html.EJS().Button("remove").Content("Remove Columns").IsPrimary(true).Render()

@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).DataBound("onBound").EnablePersistence(true).Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("CustomerID").HeaderText("Customer Name").Width("170").Add();
    col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();

}).AllowPaging(true).PageSettings(page => page.PageCount(5)).Render()

<script>
    function onBound(args) {
        var cloned = this.addOnPersist;
        this.addOnPersist = function (key) {
            key = key.filter(item => item !== "columns");
            return cloned.call(this, key);
        };
    }

    document.getElementById('add').onclick = function () {
        var obj = { field: "Freight", headerText: 'Freight', width: 120 }
        document.getElementById('Grid').ej2_instances[0].columns.push(obj); //you can add the columns by using the Grid columns method
        document.getElementById('Grid').ej2_instances[0].refreshColumns();
    }

    document.getElementById('remove').onclick = function () {
        document.getElementById('Grid').ej2_instances[0].columns.pop();
        document.getElementById('Grid').ej2_instances[0].refreshColumns();
    }

</script>
Copied to clipboard
public IActionResult Index()
 {
    var orders = OrderDetails.GetAllRecords();
    ViewBag.Datasource = orders;            
    return View();
 }

Persist the Grid column template, header template, and headerText

By default, the Grid properties such as column template, header text, header template, column formatter, and value accessor will not persist when EnablePersistence is set to true. Because the column template and header text can be customized at the application level.

If you wish to restore all these column properties, then you can achieve it by cloning the grid’s columns property using JavaScript Object’s assign method and storing this along with the persist data manually. While restoring the settings, this column object must be assigned to the grid’s columns property to restore the column settings as demonstrated in the following sample.

razor
column-persist.cs
Copied to clipboard
@Html.EJS().Button("restore").Content("Restore").IsPrimary(true).Render()

@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowFiltering(true).EnablePersistence(true).Columns(col =>
{

    col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("CustomerID").HeaderText("Customer Name").Width("170").HeaderTemplate("#customertemplate").Add();
    col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").Template("#template").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();

}).AllowPaging(true).PageSettings(page => page.PageCount(5)).Render()

<script>
document.getElementById('restore').onclick = function () {
    var savedProperties = JSON.parse(document.getElementById('Grid').ej2_instances[0].getPersistData());
    var gridColumnsState = Object.assign([], document.getElementById('Grid').ej2_instances[0].getColumns());
    savedProperties.columns.forEach(function (col) {
        var headerText = gridColumnsState.find(function (colColumnsState) { return colColumnsState.field === col.field; })['headerText'];
        var colTemplate = gridColumnsState.find(function (colColumnsState) { return colColumnsState.field === col.field; })['template'];
        var headerTemplate = gridColumnsState.find(function (colColumnsState) { return colColumnsState.field === col.field; })['headerTemplate'];
        col.headerText = 'Text Changed';
        col.template = colTemplate;
        col.headerTemplate = headerTemplate;
    });
        console.log(savedProperties);
        document.getElementById('Grid').ej2_instances[0].setProperties(savedProperties);
}
</script>

<script id="template" type="text/x-template">
    <a rel='nofollow' href="https://en.wikipedia.org/wiki/${Freight}"><span class="e-icons e-Reply"></span></a>
</script>
  
<script id="customertemplate" type="text/x-template">
    <span class="e-icons e-header" ></span>
    Customer ID
</script>
  
<style>
    .e-Reply:before {
        content: '\e815';
    }
  
    .e-header:before {
        content: '\ea9a';
    }
</style>
Copied to clipboard
public IActionResult Index()
 {
    var orders = OrderDetails.GetAllRecords();
    ViewBag.datasource = orders;            
    return View();
 }