Warning the user before leaving the page !!!
Difficulty Level : Intermediate
You might have seen in many of the web form pages to warn the user before closing the page.When somebody refreshes the page, then there is a chance for loosing all filled data. In that case it is very helpful.
Page life cycle includes two events like onunload and onbeforeunload. For this case you need to bind the script function in window. Onbeforeunload so that it will be called when page is unloading.
Again this warning should not be fired when you are actually submitting the page. For that set a boolean value (e.g. shouldsubmit) to submit the page.
Following is the code :
<script type="text/javascript">
var shouldsubmit = false; // Represent the button should ask for confirmation or not.
window.onbeforeunload = confirmUnloading;
// Funcion called before unloading of the page.
function confirmUnloading()
{
if (!shouldsubmit)
{
return "If you have any unsaved data in the current page, it will be lost.";
}
}
</script>
<asp:Button ID="btnSubmit" runat="server"
Text="Submit"
CssClass = "btnPrimary"
OnClientClick="javascript:shouldsubmit=true;"
ToolTip="Submit Page"/>