Show Confirmation Popup When User Leaves the Page with Unsaved Grid Changes
Environment
Product | Telerik UI for ASP.NET MVC Grid |
Progress Telerik UI for ASP.NET MVC version | 2024.4.1112 |
Description
How can I detect changes in an InLine editable Grid when the user tries to leave the page and prompt the user with a warning message about the unsaved changes?
Solution
To detect the changes in the Grid when the user attempts to navigate away from the page with the Grid, you can check whether there has been a change in the Grid's DataSource. If at least one change occurs, show the prompt.
- Handle the
beforeunload
event of the current window. - Get a reference to the Grid and access its DataSource.
- Check the
dirty
flag of the data items, which indicates that the data item has been changed. - Show the popup if at least one change occurs.
@(Html.Kendo().Grid<ProductViewModel>()
.Name("grid")
.Editable(editable => editable.Mode(GridEditMode.InLine))
...// Additional configuration.
)
$(document).ready(function () {
$(window).bind("beforeunload", function (event) {
var gridDS = $('#grid').getKendoGrid().dataSource; // Access the Grid's DataSource.
if (dataSourceHasChanges(gridDS)) {
return "You have unsaved changes. Are you sure you want to leave this page?"; // Show the popup.
}
});
});
function dataSourceHasChanges(ds) { // Check the Grid's DataSource for changes.
var dirty = false;
$.each(ds.data(), function () {
if (this.dirty == true) {
dirty = true;
}
});
return dirty;
}