I am hooking the window.onbeforeunload event in an aspx page. I need that not to fire if I page a GridView that's in an UpdatePanel on the same page.
I have tried hooking the PageRequestManager's initializeRequest event but this fires too late, i.e. after onbeforeunload. I have also tried checking PageRequestManager.get_isInAsyncPostBack() in my onbeforeunload handler but that returns false too, gah!
I have read this SO thread :
But that doesn't make sense to me other than GridView page links cause an unload whereas buttons in a GridView column do not? Anybody know how to solve this? I'm guessing only way is to attach client-side click handler to all the GridView's page anchors to set some boolean flag, but I'm not sure how to accomplish that in a reliable manner.
Ok JQuery to the rescue!
<script type="text/javascript">
var flag = true;
window.onbeforeunload = beforeUnloading;
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(initPagers);
function initPagers() {
$(".gridViewPagerStyle").click(function() { flag = false; });
}
function beforeUnloading(){
if(flag)
return "unloading";
flag = true;
}
</script>
:
:
<asp:GridView ... PagerStyle-CssClass="gridViewPagerStyle" ... />
:
:
Set a Css class for all pager links, use that to append javascript click handlers that set a flag when clicked, use flag to avoid onbeforeunload