aspx:
<script type="text/javascript">
window.onbeforeunload = function (e) {
if (unsavedData()) {
return "Exit page?";
}
}
function unsavedData() {
//logic for unsaved data here
//let's just return true for this example
return true;
}
</script>
<asp:UpdatePanel ID="updatePnlContent" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="false">
<ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSave" EventName="Click" />
<%-- triggers for other buttons --%>
</Triggers>
<ContentTemplate>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click"/>
<asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click"/>
<%-- Other fields and buttons --%>
</ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
code behind
protected void btnSave_Click(object sender, EventArgs e)
{
//save data
}
protected void btnCancel_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
If I click the Cancel button and there are unsaved data, I'd get a prompt to click OK to continue or Cancel to stay on this page, as expected. However, when I press Cancel to stay on this page, I get an unspecified error in one of Microsoft AJAX javascript.
What I think happened is that the OnCilck event is fired before the window.onbeforeunload function. How can I make sure that the OnClick event only fires if the user clicked OK to continue and not when Cancel to stay on this page is clicked?