This is a migrated thread and some comments may be shown as answers.

Attemping to retain grid options with setOptions() not working

2 Answers 586 Views
Grid
This is a migrated thread and some comments may be shown as answers.
John
Top achievements
Rank 1
John asked on 19 Nov 2015, 07:48 PM

I am attempting to use setOptions() on a grid to save changes a user makes to a grid (page size, page, filter, sort, etc.) then restore those changes when the user comes back to the page.  I see numerous examples of this working in forum threads but I cannot get the examples working so I must be doing something wrong.  The saving of the grid options seems to be working fine but when I return to the page I'm getting "undefined" when I try to get a reference to my grid (see attached image).  Any help would be appreciated as I have spent a good day on this and cannot get it working.

Other threads where I see setOptions being used successfully.

http://www.telerik.com/forums/retaining-page-size

http://www.telerik.com/forums/persist-state-issues

http://www.telerik.com/forums/excel-export-settings-don't-work-after-setoptions()

 

My Javascript

    var localStorageKey = "MainTransferInOptions";
    var areOptionsLoaded = false;
     
    $(window).ready(function (e) {
        loadGridOptions(undefined);
    });
 
    function bindSaveRestoreCliks() {
        $("#save").click(function (e) {
            e.preventDefault();
            var grid = $("#MainGrid").data("kendoGrid");
            var dataSource = grid.dataSource;
            var state = {
                page: dataSource.page(),
                pageSize: dataSource.pageSize(),
                sort: dataSource.sort(),
                filter: dataSource.filter()
            };
            localStorage[localStorageKey] = kendo.stringify(state);
        });
 
        $("#load").click(function (e) {
            e.preventDefault();
            loadGridOptions(e);
        });
    }
 
    function loadGridOptions(e) {
        if (e == undefined || e.type == "click" || (!areOptionsLoaded && e.type == "read")) {
            var grid = $("#MainGrid").data("kendoGrid");
            var state = localStorage[localStorageKey];
            if (state) {
                var data = JSON.parse(state);
                var options = grid.options;
                options.dataSource.page = data.page;
                options.dataSource.pageSize = data.pageSize;
                options.dataSource.sort = data.sort;
                options.dataSource.filter = data.filter;
                grid.destroy();
                $("#MainGrid").empty().kendoGrid(options);
            }
            else if (!areOptionsLoaded && e == undefined) {
                //grid.dataSource.read();
            }
 
            bindSaveRestoreCliks();
            areOptionsLoaded = true;
        }
    }
</script>

 

My Controller

public class HomeController : Controller
{
    private readonly IDbConnection _db = new SqlConnection(ConfigurationManager.ConnectionStrings["Reporting"].ConnectionString);
 
    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";
        var data = GetData();
        return View(data);
    }
 
    public ActionResult About()
    {
        ViewBag.Message = "Your app description page.";
 
        return View();
    }
 
    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";
 
        return View();
    }
 
    public ActionResult GridRead([DataSourceRequest]DataSourceRequest request)
    {
        var data = GetData();
        var serializer = new JavaScriptSerializer();
        var result = new ContentResult();
        serializer.MaxJsonLength = Int32.MaxValue;
        result.Content = serializer.Serialize(data);
        result.ContentType = "application/json";
        return result;
    }
 
    private IEnumerable<EngineFamily> GetData()
    {
        return _db.Query<EngineFamily>("dbo.uspGetEngineFamilyInformation", commandType: CommandType.StoredProcedure);
    }   
}

 

My Grid

<a href="#" class="k-button" id="save">Save Grid Options</a>
<a href="#" class="k-button" id="load">Load Grid Options</a>
<a href="#" class="k-button" id="reset">Clear Saved Grid Options</a>
@{ Html.Kendo().Grid(Model)
        .Name("MainGrid")
        .ColumnMenu(column => column.Columns(true))
        .Reorderable(reorder => reorder.Columns(true))
        .Sortable(sortable => sortable.Enabled(true).SortMode(GridSortMode.SingleColumn).AllowUnsort(true))
        .Pageable(pageable => pageable.Enabled(true).Refresh(true).ButtonCount(5).PageSizes(true).PageSizes(new int[] { 5, 10, 20, 50 }))
        .Filterable(filtering => filtering.Enabled(true))
        .Selectable(s => s.Mode(Kendo.Mvc.UI.GridSelectionMode.Single).Type(GridSelectionType.Row))
        //.Events(events => events.Change("onChange"))
        .DataSource(dataSource => dataSource
            .Ajax()
            .Read(read => read.Action("GridRead", "Home"))
            .ServerOperation(false)
            )
            //.AutoBind(false)
         .Columns(columns =>
         {
             columns.Bound(e => e.EngineFamilyNumber)
                 .Width(200)
                 .HtmlAttributes(new {style = "text-align:left"})
                 .Title("Engine Family Number")
                 .Filterable(filter => filter.Extra(false));
             columns.Bound(e => e.Authority)
                 .Width(100)
                 .HtmlAttributes(new {style = "text-align:left"})
                 .Title("Authority")
                 .Filterable(filter => filter.Extra(false));
             columns.Bound(e => e.ValidFrom)
                 .Width(100)
                 .HtmlAttributes(new {style = "text-align:left"})
                 .Title("Valid From")
                 .Filterable(filter => filter.Extra(false));
             columns.Bound(e => e.ValidTo)
                 .Width(100)
                 .HtmlAttributes(new {style = "text-align:left"})
                 .Title("Valid To")
                 .Filterable(filter => filter.Extra(false));
         })           
         .Render();
}

2 Answers, 1 is accepted

Sort by
0
Radoslav
Telerik team
answered on 23 Nov 2015, 08:17 AM
Hi John,

I reviewed the posted code and it looks correct. Also I tried to reproduce the described issue on my side but with no avail. I am sending you a simple example based on your code. Please check it out and let me know what differs in your case.

Looking forward for your reply.

Regards,
Radoslav
Telerik
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
0
John
Top achievements
Rank 1
answered on 23 Nov 2015, 04:41 PM

Your code does not reproduce the issue I'm having.  The difference between your code and mine is in the Read action on the controller.

I have

 

public ActionResult EngineFamilyRead([DataSourceRequest]DataSourceRequest request)
{
    var data = _engineFamilyRepository.GetAll().ToList();
    var serializer = new JavaScriptSerializer();
    var result = new ContentResult();
    serializer.MaxJsonLength = Int32.MaxValue;
    result.Content = serializer.Serialize(data);
    result.ContentType = "application/json";
    return result;
}

 

You have

 

public ActionResult EngineFamilyRead([DataSourceRequest]DataSourceRequest request)
{
     return Json(_engineFamilyRepository.GetAll().ToDataSourceResult(request));
}

  

When I changed my controller code to match yours the grid was no longer undefined.

Thank you for the sample project and you help.

Tags
Grid
Asked by
John
Top achievements
Rank 1
Answers by
Radoslav
Telerik team
John
Top achievements
Rank 1
Share this question
or