New to Telerik UI for ASP.NET MVC? Download free 30-day trial

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.

  1. Handle the beforeunload event of the current window.
  2. Get a reference to the Grid and access its DataSource.
  3. Check the dirty flag of the data items, which indicates that the data item has been changed.
  4. 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;
    }

More ASP.NET MVC Grid Resources

See Also

In this article