I have a Kendo Grid as per the code below
@(Html.Kendo().Grid<ReportCompetencyViewModel>()
.Name("listGrid")
.BindTo(Model.ReportCompetency.OrderBy(x => x.DisplayOrder))
.Columns(columns =>
{
columns.Bound(c => c.Code).ClientHeaderTemplate("Code");
columns.Bound(c => c.DisplayName).ClientHeaderTemplate("Description");
columns.Bound(c => c.IEC).ClientHeaderTemplate("IEC");
columns.Bound(c => c.Active)
.ClientTemplate("#if(Active) {# <i class='fas fa-check'></i> # } else {# <i class='fas fa-times'></i> #} #")
.ClientHeaderTemplate("Active")
.HtmlAttributes(new { @class = "text-center" })
.Width(100);
})
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.Sortable()
.Filterable()
.Groupable()
.NoRecords(n => n.Template("<p>There are no records to display.</p>"))
.HtmlAttributes(new { style = "width:100%;" })
.Selectable(selectable => selectable
.Mode(GridSelectionMode.Single)
.Type(GridSelectionType.Row))
.Events(events => events
.Change("lu.onChange")
)
.Pageable(p =>
{
p.PageSizes(new[] { 5, 10, 30, 50, 100 });
})
.DataSource(dataSource => dataSource
.Ajax()
.Group(g => g.Add(x => x.IEC))
.PageSize(50)
.ServerOperation(false)
.Read(r => r.Action("RefreshCompetenciesGridData", "ReportLookup").Data("lu.sendAntiForgery"))
)
)
I have a partial that has a sortable element in it also as below.
@(Html.Kendo().Sortable()
.For($"#{@Model.GridId}")
.Filter("table > tbody > tr")
.Cursor("move")
.PlaceholderHandler("sg.placeholder")
.ContainerSelector($"#{Model.GridId} tbody")
.Events(events => events.Change("sg.onChange"))
)
The onchange event is
onChange = (e: any) => {
var grid: kendo.ui.Grid = $("#" + this.gridId).data("kendoGrid"),
skip = grid.dataSource.skip(),
oldIndex = e.oldIndex + skip,
newIndex = e.newIndex + skip,
data = grid.dataSource.data(),
dataItem = grid.dataSource.getByUid(e.item.data("uid"));
grid.dataSource.remove(dataItem);
grid.dataSource.insert(newIndex, dataItem);
console.log(newIndex);
if (this.showSaveNotification && $("#" + this.warningDivId).length) {
$("#" + this.warningDivId).slideDown();
this.showSaveNotification = false;
}
}
The sortable element works great, the majority of the time.
When performing a re-order, opening a kendo window and performing a save action the grid is refreshed with the updated data in a TypeScript class as per code below.
save = (model: any) => {
var _self = this;
var girdOrderArray = new Array();
if ($("#grid-reorder-warning").length && $("#grid-reorder-warning").is(":visible")) {
var grid = $("#" + this.girdName).data("kendoGrid");
var dataItems = grid.dataItems() as any;
$.each(dataItems,
(idx: number, dataItem) => {
var di = idx + 1;
var id = dataItem.id === undefined ? dataItem.Id : dataItem.id; // Changing the display order appears to also change the dataItem from Id to id.
girdOrderArray.push({ Id: id, DisplayOrder: di });
});
}
var da = new Tmsp.AjaxDataAccessLayer(Tmsp.Enums.AjaxCallType.Post,
Tmsp.Enums.AjaxDataType.Json,
this.saveUrl,
JSON.stringify(model),
"application/json; charset=utf-8",
{ "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
true, true);
da.ajaxCall(data => {
_self.closeWindow();
if ($("#grid-reorder-warning").is(":visible")) {
grid.dataSource.read().then(() => {
var dataItems = grid.dataItems();
var arr = new Array() as any;
$.each(dataItems,
(idx, dataItem: any) => {
var id = dataItem.Id === null ? dataItem.id : dataItem.Id;
var gridOrderObj = jQuery.grep(girdOrderArray,
function (gridOrderObj: any) { return gridOrderObj.Id == id });
dataItem.set("DisplayOrder", gridOrderObj[0].DisplayOrder);
});
grid.dataSource.sort({ field: "DisplayOrder", dir: "Desc" });
});
} else {
_self.refreshGrid();
}
return false;
}, (xhr, status, errorThrown) => {
console.log(xhr);
console.log(status);
console.log(errorThrown);
});
return false;
}
This saves, and reorders teh grid accordingly by the DisplayOrder which is great and what I need. However, when I try and reorder anything else after this the reordered item gives me the new index, but isnt actually changed on the grid.
However, if I refresh the grid through other means, the re-oredering works perfectly.
So, my question, as I need to keep the display order as is prior the the save, how do I acheive this.
Things I have tried
Ah ha!!!
I have found the answer and Telerik do not make it easy to find how to do things.
using the link that I have here https://docs.telerik.com/kendo-ui/controls/interactivity/sortable/how-to/persist-order-in-localstorage I have been able to find the code that I need in order to persist the state.
I believe in one of my attempts last week that I was actually quite close, although not perfect.
this is how the on change event looks now
onChange = (e: any) => {
var grid: kendo.ui.Grid = $("#" + this.gridId).data("kendoGrid"),
skip = grid.dataSource.skip(),
oldIndex = e.oldIndex + skip,
newIndex = e.newIndex + skip,
data = grid.dataSource.data(),
dataItem = grid.dataSource.getByUid(e.item.data("uid"));
grid.dataSource.remove(dataItem);
grid.dataSource.insert(newIndex, dataItem);
console.log(newIndex);
localStorage.setItem("sortableData", kendo.stringify(data)); //set the updated in local storage
if (this.showSaveNotification && $("#" + this.warningDivId).length) {
$("#" + this.warningDivId).slideDown();
this.showSaveNotification = false;
}
}
the new line in here is
localStorage.setItem("sortableData", kendo.stringify(data)); //set the updated in local storage
the new save and refresh gird looks like this
saveNewOrder = () => {
var model = new Array();
var grid: kendo.ui.Grid = $("#" + this.gridId).data("kendoGrid");
var _self = this;
var dataItems = grid.dataItems() as any;
$.each(dataItems,
(idx : number, dataItem) => {
var di = idx + 1;
var id = dataItem.Id === null ? dataItem.id : dataItem.Id;
model.push({ Id: id , DisplayOrder: di});
});
var da = new AjaxDataAccessLayer(Tmsp.Enums.AjaxCallType.Put,
Tmsp.Enums.AjaxDataType.Json,
this.saveUrl,
JSON.stringify(model),
"application/json; charset=utf-8",
{ "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
true,
true);
da.ajaxCall(data =>{
_self.refreshGridOrder();
}, (xhr, textStatus, errorThrown) => {
////console.log(xhr);
////console.log(textStatus);
////console.log(errorThrown);
});
}
refreshGridOrder = () => {
var grid = $("#" + this.gridId).data("kendoGrid");
grid.dataSource.read().then(() => {
var data = JSON.parse(localStorage.getItem("sortableData"));
grid.dataSource.data(data);
$("#" + this.warningDivId).slideUp();
this.showSaveNotification = true;
});
}
The other thing to remember is that as this is used from multiple locations is to also clear the local storage at the point of document ready.