FBryant87 FBryant87 - 3 months ago 32
jQuery Question

.NET MVC - "beforeunload" event with server-side check

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 () {
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 problem with Chrome


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