When user leaves the page, we can show an confirmation javascript window, if user click "No", he will stay on the page. This works on every links on the page, the back button and even the close window action can be canceled. The key part of this solution is tie "window.onbeforeunload" event with a javascript function. The following function shows how to emit the javascript function from asp.net code behind.
protected void EmitJsConfirm()
{
string jScript = String.Empty;
if(!Page.IsClientScriptBlockRegistered("jsConfirm"))
{
jScript = String.Format(@"<SCRIPT language='javascript'>var needToConfirm = true;function confirmExit()
{{if (needToConfirm){{return '{0}';}}}}
window.onbeforeunload = confirmExit;</SCRIPT>",_jsConfirmMsg);
Page.RegisterClientScriptBlock("jsConfirm",jScript);
}
}
However, this confirmation message will show up even the page postback to itself, such as user click button to sumbit or a dropdown list auto postback. So we need a way to prevent these control's events from showing the confirmation message. Following function will do the trick. Note that we treat control differently, if it's dropdown we use "onChange", otherwise we use "onClick".
protected void ExcludeControlFromConfirm(params WebControl[] controls)
{
foreach(WebControl c in controls)
{
if(c is DropDownList)
c.Attributes.Add("onChange","needToConfirm = false;");
else
c.Attributes.Add("onClick","needToConfirm = false;");
}
}
No comments:
Post a Comment