Can I prevent [removed] from being called when doing an AJAX call

后端 未结 9 1669
北恋
北恋 2020-12-24 03:22

I have an AJAX-based grid control.

We hook into the window.onbeforeunload event to check if they have unsaved data and if so present them with a message \"Are you s

9条回答
  •  忘掉有多难
    2020-12-24 04:06

    If you're talking about ASP.NET AJAX partial postbacks, then I encountered this behavior today too, doing the exact same thing. (If you're not, ignore my post completely.)

    In my experience so far, it seems like if your partial postback is triggered by an input, it won't fire onbeforeunload during a partial postback, but if the partial postback is triggered by a hyperlink, it will. It seems like the browser assumes you're navigating away if you click on anything in an anchor tag (only tested in IE and FireFox but yeah).

    Whether or not the page has a certain hidden field is already what I was using to determine client-side when it's appropriate to show the navigate away warning, so I was able to fix this very simply by adding a check of the hidden field's value to my onbeforeunload's if condition, and hooking into the PageRequestManager's BeginRequest and EndRequest handlers to set the value. That effectively disables the warning during partial postbacks. You could add more complicated logic here if there were more specific things you wanted to check.

    Here's a really over-simplified code sample. (sorry if i pared and censored to the point where it doesn't work but it should give you an idea.)

    window.onbeforeunload = checkNavigateAway;
    
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(onBeginRequest);
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(onEndRequest);
    
    function onBeginRequest(sender, args) {
        var navigateAwayFlag = $("input[id*='navigateAwayValue']");
        if (navigateAwayFlag.length > 0) {
            navigateAwayFlag[0].value = "false";
        }
    }
    
    function onEndRequest(sender, args) {
        var navigateAwayFlag = $("input[id*='navigateAwayValue']");
        if (navigateAwayFlag.length > 0) {
            navigateAwayFlag[0].value = "true";
        }
    }
    
    function checkNavigateAway() {
        var navigateAwayFlag = $("input[id*='navigateAwayValue']");
        if (navigateAwayFlag.length > 0 && navigateAwayFlag[0].value == "true")
        {
            return "Warning Text";
        }
    }
    

    Edit: Bad news. The above doesn't seem to work in IE6. It seems like it fires events in a different order than Firefox, so the onbeforeunload fires before the AJAX beginRequest... May have to find a way to change the flag's value via the hyperlink click before the onbeforeunload fires.

提交回复
热议问题