We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Save column positioning with grid state

Hi,

This is regarding an earlier query that I had https://www.syncfusion.com/forums/145592/save-grid-state-column-visibility-filtering-sorting-in-database. I am attempting to allow the user to save their grid state (filtering, sorting, grouping, etc) but I want the user to save the full state of their grid including column positioning. I have my grid so that users are allowed to column reordering. Currently, users are able to save the grid state for sorting, filtering, and grouping but not reordering. How do I allow them to save the order of their columns along with the rest of the grid state?

Here's my code:

<div class="padding-10-px">

    <div>

        <h1>

            Project Summary

        </h1>

    </div>

    <div style="margin-top: 25px; margin-bottom: 25px; display: flex; justify-content:space-between;">

        <div>

            <button title="Save your current view" id="btn-save-grid-state" class="btn btn-primary">Save View</button>

            <button title="Restore the grid to your last custom saved view" id="btn-restore-grid-state" class="btn btn-success">Restore Grid</button>

            <button title="Reset the grid to the default settings" id="btn-reset-grid-state" class="btn btn-danger">Reset to Default</button>

        </div>

        <div>

            <button id="btn-add-project" class="btn btn-info">Add Project</button>

        </div>

    </div>

    <div class="control-section" style="position:relative;">

        @{

            List<object> toolbarItems = new List<object>();

            toolbarItems.Add("Add");

            toolbarItems.Add("Edit");

            toolbarItems.Add("Delete");

            toolbarItems.Add("Update");

            toolbarItems.Add("Cancel");

            toolbarItems.Add("Search");

            toolbarItems.Add("ExcelExport");

            toolbarItems.Add("ColumnChooser");

            //toolbarItems.Add(new { text = "Click", tooltipText = "Click", id = "Click", prefixIcon = "e-expand" });

        }


        @*<div style="height: 40px;">

            @Html.EJS().Button("clear").Content("Clear Search").Render()

        </div>*@


        @(Html.EJS().Grid<ProjectMvcModel>("Grid")

        //.DataBound("dataBound")

        //.Height("300")

        .Width("100%")

        .Height("600")

        //.Height("600")

        .DataSource(DataManager => { DataManager.Url("/Proj/UrlDataSource").CrudUrl("/Proj/CrudUpdate").Adaptor("UrlAdaptor"); })

        .AllowResizing(true)

        .AllowFiltering()

        .FilterSettings(filter => filter.Type(Syncfusion.EJ2.Grids.FilterType.Excel))

        .AllowSelection()

        .AllowGrouping()

        .AllowSorting(true)

        .AllowReordering()

        .ShowColumnChooser(true)

        .ShowColumnMenu(true)

        .AllowExcelExport(true)

        .EnableAltRow()

        .DetailTemplate("#rowDetailTemplate")

        .ToolbarClick("toolbarClick")

        .GroupSettings(group => { group.ShowDropArea(false).ShowUngroupButton(true).ShowGroupedColumn(true).ShowToggleButton(true); })

        //.SearchSettings()

        //.FrozenRows(1)

        .Columns(col =>

        {

            col.Field(p => p.Id).Width("60").IsPrimaryKey(true).IsIdentity(true).Type("number").Width("120").AllowFiltering(false).Add();

            col.HeaderText("Project Details").Visible(true).Template(" <a rel='nofollow' href='ProjectDetailsMaster?id=${Id} '>View</a> ").Width("140").AllowEditing(false).Add();

            col.Field(p => p.ProjName).AllowSorting(true).AllowFiltering(false).Width("175").Add();

            /*REQUIRED*/

            col.Field(p => p.ProjDesc).Width("325").ValidationRules(new { required = "true" }).AllowFiltering(false).Add();

            /*REQUIRED*/

            col.Field(p => p.GroupName).EditType("dropdownedit").Edit(new { @params = GroupNameDropdown }).Width("175").ValidationRules(new { required = "true" }).Add();

            /*REQUIRED*/

            col.Field(p => p.PortfolioName).EditType("dropdownedit").Edit(new { @params = PortfolioNameDropdown }).Width("175").ValidationRules(new { required = "true" }).Add();

            /*REQUIRED*/

            col.Field(p => p.PortLead).EditType("dropdownedit").Edit(new { @params = PortfolioLeadsDropdown }).Width("180").ValidationRules(new { required = "true" }).Add();

            /*REQUIRED*/

            col.Field(p => p.ProjLead).EditType("dropdownedit").Edit(new { @params = ProjectLeadsDropdown }).Width("180").ValidationRules(new { required = "true" }).Add();

            /*REQUIRED*/

            col.Field(p => p.ProgramName).EditType("dropdownedit").Edit(new { @params = ProgramNameDropdown }).Width("180").ValidationRules(new { required = "true" }).Add();

            /*REQUIRED*/

            col.Field(p => p.AssignedDate).Format("yMd").EditType("datepickeredit").Width("175").ValidationRules(new { required = "true" }).Add();

            /*REQUIRED*/

            col.Field(p => p.StatusName).EditType("dropdownedit").Edit(new { @params = StatusNameDropdown }).Template("#statusTemplate").Width("175").ValidationRules(new { required = "true" }).Add();

            col.Field(p => p.DecisionTypeName).EditType("dropdownedit").Edit(new { @params = DecisionNameDropdown }).Width("180").Add();

            col.Field(p => p.JRCDate).Format("yMd").EditType("datepickeredit").Width("175").Add();

            /*REQUIRED*/

            col.Field(p => p.PriorityName).EditType("dropdownedit").Edit(new { @params = PriorityNameDropdown }).Width("175").Add();



            col.Field(p => p.CompletionDate).Format("yMd").EditType("datepickeredit").Width("200").Visible(false).Add();

            col.Field(p => p.CreatedOn).Width("200").Format("yMd").IsIdentity(true).Visible(false).Add();

            col.Field(p => p.CreatedBy).Width("200").IsIdentity(true).Visible(false).Add();

            col.Field(p => p.ModifiedOn).Width("200").Format("yMd").IsIdentity(true).Visible(false).Add();

            col.Field(p => p.ModifiedBy).Width("180").IsIdentity(true).Visible(false).Add();

            col.Field(p => p.KSNLink).Template("#ksnLinkTemplate").Visible(false).Width("180").Add();

        })

            //.EnableVirtualization()

            .ActionComplete("actionComplete")

            .AllowPaging()

            .QueryCellInfo("onQueryCellInfo")

            .PageSettings(page => page.PageCount(5))

            .EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).ShowDeleteConfirmDialog(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal); })

            .Toolbar(toolbarItems)

            //(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel", "ColumnChooser", "ExcelExport", "Search" })

            .PageSettings(page =>

            {

                page.PageSize(25);

                page.PageSizes(new List<string>() { "10", "25", "50", "100", "All" });

            })

            //.QueryCellInfo("OnQueryCellInfo")

            .DataBound("OnDataBound")

            .Render()

        )

    </div>

</div>




3 Replies

TS Thavasianand Sankaranarayanan Syncfusion Team September 13, 2019 05:19 AM

Hi Hatem,  

As per your query, we have saved the persist data in the Grid while we reordering the Grid. You can also save and update the Grid state for reordering properties in the EJ2 Grid. Please refer the below sample for more information. 

[index.cshtml] 
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.datasource).AllowReordering(true).AllowSorting(true).AllowFiltering(true).AllowPaging(true).Columns(col => 
{ 
    col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("100").Add(); 
    col.Field("EmployeeID").HeaderText("Employee ID").Width("120").Add(); 
    col.Field("OrderDate").HeaderText("Order Date").Width("120").Format("yMd").Add(); 
}).FilterSettings(filter => { filter.Type(Syncfusion.EJ2.Grids.FilterType.Menu); }).Render() 
 
<script type="text/javascript"> 
    function store(e) {  // button click 
        var grid = document.getElementById("Grid").ej2_instances[0]; 
        var persistData = JSON.stringify({ persistData: grid.getPersistData() }); // Grid persistData 
        var ajax = new ej.base.Ajax({ // used our ajax to send the stored persistData to server 
            url: "/Home/StorePersistData", 
            type: "POST", 
            contentType: "application/json; charset=utf-8", 
            datatype: "json", 
            data: persistData  
        }); 
        ajax.send(); 
    } 
    function reset(e) { // button click 
        var ajax = new ej.base.Ajax({ // used our ajax to send the retrive the persistData from server 
            url: "/Home/restore", 
            type: "POST", 
            contentType: "application/json; charset=utf-8" 
        }); 
        ajax.send(); 
        ajax.onSuccess = function (result) { 
            var grid = document.getElementById("Grid").ej2_instances[0]; 
            var state = JSON.parse(result); 
            grid.setProperties({ // provide the retrived state to Grid through the setProperties method 
                filterSettings: state.filterSettings, 
                sortSettings: { columns: state.sortSettings.columns } 
            }, false); 
            grid.setProperties({ 
                columns: state.columns 
            })  
        } 
    } 


Please get back to us, if you need further assistance. 

Regards, 
Thavasianand S.  



HM Hatem Muhsen September 25, 2019 09:10 AM

I copied and pasted my restore function below. It works except for one thing, the column positioning. If I restore the columns the way that you suggested, it messes up the headers (retrieving the database field names) and it causes the data to completely disappear. How do I get the column (visibility and positioning) back from the persist data without causing the data to disappear and keeping the headers the way they are?

 function restoreGridState() {

        var grid = document.getElementById("Grid").ej2_instances[0];


        // Get grid state from server via AJAX request

        $.ajax({

            type: 'GET',

            url: '@Url.Action("RestoreGridState", "Proj")',

            success: function (data) {

                // Update Client Grid State

                if (data) {

                    var gridStateData = JSON.parse(JSON.parse(data));


                    grid.setProperties({

                        columnModel: gridStateData.columns,

                        sortSettings: { columns: gridStateData.sortSettings.columns },

                        filterSettings: gridStateData.filterSettings,

                        pageSettings: { pageSize: gridStateData.pageSettings.pageSize, currentPage: gridStateData.pageSettings.currentPage, pageCount: gridStateData.pageSettings.pageCount },

                        searchSettings: { fields: gridStateData.searchSettings.fields, key: gridStateData.searchSettings.key }


                    }, true)


                    grid.setProperties({

                        groupSettings: { columns: gridStateData.groupSettings.columns }

                    })


                    grid.refreshHeader();

                }

            },

        });

    }




PS Pavithra Subramaniyam Syncfusion Team September 26, 2019 04:26 AM

Hi Hatem, 
 
Query: How do I get the column (visibility and positioning) back from the persist data without causing the data to disappear and keeping the headers the way they are? 
 
We have validated your query we have removed following properties column’s headerText, column template, filter template, editTemplate for certain cases and prevent the JSON circular reference issue property from getPersistData method. For this reason, the headerText is not persisted in getPersistData method. So the column Field value is set to column header. Here, we have modified the sample to set the proper headerText for corresponding columns. Refer the below code snippets and sample for your reference. 
 
[code snippets] 
... 
 
<script type="text/javascript"> 
    function store(e) {  // button click 
        var grid = document.getElementById("Grid").ej2_instances[0]; 
       for (var i = 0; i < grid.columns.length; i++) { 
            grid.columns[i].backupHeader = grid.columns[i].headerText;    //take headerText duplicate to store in another property 
        } 
       var persistData = JSON.stringify({ persistData: grid.getPersistData() }); // Grid persistData 
        var ajax = new ej.base.Ajax({ // used our ajax to send the stored persistData to server 
            url: "/Home/StorePersistData", 
            type: "POST", 
            contentType: "application/json; charset=utf-8", 
            datatype: "json", 
            data: persistData 
        }); 
        ajax.send(); 
    } 
    function reset(e) { // button click 
        var ajax = new ej.base.Ajax({ // used our ajax to send the retrieve the persistData from server 
            url: "/Home/restore", 
            type: "POST", 
            contentType: "application/json; charset=utf-8" 
        }); 
        ajax.send(); 
        ajax.onSuccess = function (result) { 
            var grid = document.getElementById("Grid").ej2_instances[0]; 
            var state = JSON.parse(result); 
            for (var i = 0; i < state.columns.length; i++) { 
                state.columns[i].headerText = state.columns[i].backupHeader;     restore headerText 
            } 
            grid.setProperties({ // provide the retrieved state to Grid through the setProperties method 
                filterSettings: state.filterSettings, 
                sortSettings: { columns: state.sortSettings.columns } 
            }, false); 
            grid.setProperties({ 
                columns: state.columns 
            }) 
        } 
    } 
</script> 
 
 
Please get back to us if you need further assistance. 
 
Regards, 
Pavithra S. 


Loader.
Live Chat Icon For mobile
Up arrow icon