by Jim
Aug 29, 2007 10:13 PM
I'm back to ASP.NET programming having fun with a highly complex user interface.
Our site uses UpdatePanels to bring in new content and we're warning on navigation away from the page - including the back button - by returning a message in onbeforeunload. But all of our ASP.NET LinkButton controls were triggering this warning, even when posting back to the same page. Here's my test page:
<%@ Page Language="vb" Strict="True" %>
<html>
<script>
var showMessage = true;
function beforeunload()
{
if (showMessage)
return "You are leaving the test page."
}
</script>
<body onbeforeunload="return beforeunload();">
<form runat="server">
<a href="javascript:function() {showMessage=false;}">Anchor</a>
<hr />
<a href="#" onclick="showMessage=false;return false;">Anchor</a>
<hr />
<asp:LinkButton runat="server">Default LinkButton</asp:LinkButton>
<hr />
<asp:LinkButton runat="server" OnClientClick="showMessage=false;">
Fixed LinkButton</asp:LinkButton>
</form>
</body>
</html>
This shows the trick to using a LinkButton with an UpdatePanel, or in any situation where the page posts back to itself. The script for turning off the message must be in the onclick, and not in the href's javascript:. The latter works in FireFox but not in IE.
This is because in Internet Explorer, the sequence of events is onclick, onbeforeunload, href, while in Firefox the sequence is onclick, href, onbeforeunload.