New to Telerik UI for ASP.NET Core? Download free 30-day trial

Persist the State of the Grid Automatically

Environment

Product Progress® Telerik UI for ASP.NET Core Grid

Description

How can I automatically persist the sort, filter, and group Grid options when the user leaves the page and keep the look of the Grid the same as the user closed the tab?

Solution

The state of the Grid is persisted in the beforeunload event handler. This way, any operation which the user performs before leaving the page is persisted. To restore the Grid state, use the document.ready event.

@(Html.Kendo().Grid<TelerikMvcApp9.Models.OrderViewModel>()
            .Name("grid")
            .Columns(columns =>
            {
                columns.Bound(p => p.OrderID).Filterable(false);
                columns.Bound(p => p.Freight);
                columns.Bound(p => p.OrderDate).Format("{0:MM/dd/yyyy}");
                columns.Bound(p => p.ShipName);
                columns.Bound(p => p.ShipCity);
            })
            .Pageable()
            .Sortable()
            .Scrollable()
            .Filterable()
            .Groupable()
            .HtmlAttributes(new { style = "height:550px;" })
            .DataSource(dataSource => dataSource
                .Ajax()
                .PageSize(20)
                .Read(read => read.Action("Orders_Read", "Grid"))
            )
        )

<script>
$(document).ready(function () {
    var options = localStorage["grid-options"];

    var grid = $("#grid").data("kendoGrid");

    if (options) {
        grid.setOptions(JSON.parse(options));
    }

    window.onbeforeunload = function() {
        localStorage["grid-options"] = kendo.stringify(grid.getOptions());

        return;
    }
});
</script>
In this article