Persisting the Grid State

This example shows how you can save and restore the grid state, including column layout, sort descriptions, and filter definitions.

Try reordering, resizing, sorting, and filtering the columns on the grid below. Then press the "Save State" button to save the state to local storage. Run the sample again and press the "Restore State" button to restore the layout that you saved.

// This file locates: "Scripts/Lesson/C1FlexGrid/PersistingState.js".
c1.documentReady(function () {
    var theGrid = wijmo.Control.getControl('#theGrid');
    var theFilter = c1.getExtender(theGrid, "theGridFilter");

    // save/restore grid state
    document.getElementById('btnSave').addEventListener('click', function () {
        var sorts = theGrid.collectionView.sortDescriptions.map(function (sort) {
            return { property: sort.property, ascending: sort.ascending };
        });

        var state = {
            columns: theGrid.columnLayout,
            filterDefinition: theFilter.filterDefinition,
            sortDescriptions: sorts
        }
        localStorage['gridState'] = JSON.stringify(state);
    });
    document.getElementById('btnRestore').addEventListener('click', function () {
        var json = localStorage['gridState'];
        if (json) {
            var state = JSON.parse(json);

            // restore column layout (order/width)
            theGrid.columnLayout = state.columns;

            // restore filter definitions
            theFilter.filterDefinition = state.filterDefinition;

            // restore sort state
            theGrid.collectionView.sortDescriptions.clear();
            for (var i = 0; i < state.sortDescriptions.length; i++) {
                var sortDesc = state.sortDescriptions[i];
                theGrid.collectionView.sortDescriptions.push(
                    new wijmo.collections.SortDescription(sortDesc.property, sortDesc.ascending)
                );
            }
        }
    });
});
using System.Web.Mvc;

namespace LearnMvcClient.Controllers
{
    public partial class C1FlexGridController : Controller
    {
        // GET: PersistingState
        public ActionResult PersistingState()
        {
            return View(Models.FlexGridData.GetSales());
        }
    }
}
@model IEnumerable<FlexGridData.Sale>

<h1>
    @Html.Raw(Resources.C1FlexGrid.PersistingState_Title)
</h1>
<p>
    @Html.Raw(Resources.C1FlexGrid.PersistingState_Text1)
</p>
<p>
    @Html.Raw(Resources.C1FlexGrid.PersistingState_Text2)
</p>
@(Html.C1().FlexGrid().Id("theGrid")
    .Bind(b=>b.Bind(Model).DisableServerRead(true))
    .Filterable(f=>f.Id("theGridFilter"))
)

<button id="btnSave" class="btn btn-default">
    @Html.Raw(Resources.C1FlexGrid.PersistingState_Text3)
</button>
<button id="btnRestore" class="btn btn-default">
    @Html.Raw(Resources.C1FlexGrid.PersistingState_Text4)
</button>