Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET MVC - "beforeunload" event with server-side check [duplicate]

In my MVC application, when a user leaves a certain page I need to prompt them with a warning like so:

    $(window).on("beforeunload", function () {
         return "You will lose changes, are you sure?"
    });

This jquery works, but first I need to check whether the user should be warned in the first place. This check is complex and needs to be performed server side (I've struggled to find an example of this). Is it possible?

I've tried an ajax post:

$(window).on("beforeunload", function () {
    $.ajax({
        type: "POST",
        url: "@Url.Action("SaveCheck")",
        async: false
        success: function (result) {
            //return a string here if saving required
        }
    });
});

But this doesn't work like above - the "beforeunload" function already returns and doesn't care about the result of the ajax post.

Is there some way I can use a calculated flag from the server to check whether the user should be warned or not before they exit?

This answer looks relevant, but does not allow you to use the result of the ajax call in the "beforeunload" function, therefore you can't warn the user: window.onbeforeunload ajax request in Chrome

like image 448
FBryant87 Avatar asked Jan 27 '26 13:01

FBryant87


1 Answers

You probably need to wait for the promise returned by the ajax call to complete. See this answer: Jquery promise wait to ajax end

like image 115
Pelle Avatar answered Jan 30 '26 07:01

Pelle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!