Thursday, July 9, 2015

Kendo MVC Grid: Persist state issue


There is a limitation for making the toolbar persistent. A note about it from the kendo docs:
An important limitation when using the setOptions method in combination with the MVC wrappers is that any toolbar or header server templates (razor syntax @) will be lost and the layout will become incorrect once the method is invoked. Those options cannot be persisted because there is no JavaScript equivalent option for them since they contain server side logic. Consider using JavaScript initialization (instead of the MVC wrapper). An alternative is to specify the same option with the JavaScript equivalent.
Here's a possible solution: Persist state issues
I'm not a developer, but ran across the same problem with using javascript. I had to put the entire template code in the grid options, instead of pointing to an HTML template. I hope that points you in the right direction.

@{
    var culture = System.Globalization.CultureInfo.CurrentCulture.ToString();
}

@helper ToolbarTemplate() {
    <[a class="k-button k-button-icontext k-grid-add" href="/Home/Read?grid-mode=insert">Add
    <[button class="k-button k-button-icontext k-grid-excel">Export to Excel
    <[button class="k-button k-button-icontext k-grid-pdf">Export to PDF
    <[a class="k-button k-button-icontext savesetting" href="/">Save Settings
    <[a class="k-button k-button-icontext loadsetting" href="/">Load Settings
    @(Html.Kendo().DropDownList()
        .Name("ExampleEditor")
        .OptionLabel("- ExampleEditor -")
        .DataTextField("Text")
        .DataTextField("Value")
        .BindTo(new List() {
            new {Text = "Item 1", Value= "1"}, 
            new {Text = "Item 2", Value= "2"} }
    ))
}

@helper HeaderTemplate() {
    My Template
}

[XXXscript type="text/x-kendo-template" id="toolbarTemplate">    
   @Html.Raw(@ToolbarTemplate().ToHtmlString().Replace("#", "\\#").Replace("

[XXXscript type="text/x-kendo-template" id="headerTemplate">    
   @Html.Raw(@HeaderTemplate().ToHtmlString().Replace("#", "\\#").Replace("

@(Html.Kendo().Grid()
    .Name("grid")
    .Columns(columns =>
    {
        columns.Bound(p => p.OrderID).HeaderTemplate(@@HeaderTemplate());
        columns.ForeignKey(p => p.EmployeeID, (System.Collections.IEnumerable)ViewData["employees"], "EmployeeID", "Name");
        columns.Bound(p => p.OrderDescription);
        columns.Bound(p => p.OrderDate).Format("{0:d}");
        columns.Bound(p => p.OrderTotal).Format("{0:c}");
        columns.Bound(p => p.IsCompleted);
        columns.Command(c =>
        {
            c.Edit();
            c.Destroy();
        });
    })
                .ToolBar(toolbar =>
                {
                    toolbar.Template(@
            @ToolbarTemplate()
        );
                })
                    .Editable(editable => editable.Mode(GridEditMode.InLine))
                    .Pageable()
                    .Sortable()
                    .Scrollable()
                    .Filterable()
                    .DataSource(dataSource => dataSource
                        .Ajax()
                        .ServerOperation(false)
                        .Model(model =>
                        {
                            model.Id(p => p.OrderID);
                            model.Field(p => p.OrderID).Editable(false);
                        })
                        .Events(e => e.RequestEnd("onRequestEnd"))
                        .Create(create => create.Action("Create", "Home").Data("sendCulture"))
                        .Destroy(destroy => destroy.Action("Delete", "Home").Data("sendCulture"))
                        .Read(read => read.Action("Read", "Home").Data("sendCulture"))
                        .Update(update => update.Action("Update", "Home").Data("sendCulture"))
                    )
                )


[XXXscript>
    $("#grid").on("click", ".savesetting", function (e) {
        var grid = $(this).closest("[data-role=grid]").data("kendoGrid");
        e.preventDefault();
        localStorage["settings"] = kendo.stringify(grid.getOptions());
    });

    $("#grid").on("click", ".loadsetting", function (e) {
        var grid = $(this).closest("[data-role=grid]").data("kendoGrid");
        e.preventDefault();
        var options = localStorage["settings"];
        if (options) {
            var parsedOptions = JSON.parse(options);
            parsedOptions.toolbar = [
                { template: $("#toolbarTemplate").html() }
            ];
            parsedOptions.columns[0].headerTemplate = $("#headerTemplate").html();
            grid.setOptions(parsedOptions);
  }
    });

    //convert dates to UTC
    function onRequestEnd(e) {
        if (e.type == "read") {
            var offsetMiliseconds = new Date().getTimezoneOffset() * 60000;
            var orders = e.response.Data;
            for (var i = 0; i < orders.length; i++) {
                orders[i].OrderDate = orders[i].OrderDate.replace(/\d+/,
                    function (n) { return parseInt(n) + offsetMiliseconds }
                 );
            }
        }
    }

    //send current culture with all ajax requests
    function sendCulture() {
        return { culture: "@culture" }
    }
[/XXX>

No comments: