0

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?

Chris Nielsen
  • 14,731
  • 7
  • 48
  • 54
Minh Nguyen
  • 179
  • 3
  • 16

1 Answers1

0

Remove the OnClick method from the Cancel button and replace it with OnClieckClick and call the unsavedData() function.

If you would like to use the OnClick as well as the OnClientClick, refer to this post for the solution: OnclientClick and OnClick is not working at the same time?

Community
  • 1
  • 1
Vishal Shah
  • 1,042
  • 8
  • 11
  • Hi vishalashah, thank you for your response. However, adding OnClientClick to call the unsavedData() function still doesn't fix the problem. The OnClick event is still firing before window.onbeforeunload. I want to add that if the button is outside of an updatepanel, I don't have this problem. Thanks. – Minh Nguyen Feb 07 '13 at 22:22
  • The issue here is UpdatePanel causes a Partial-Page update and thus your window.onBeforeUnload so the unload event doesn't fire on a partial page update. Check out http://www.asp.net/ajax/documentation/live/overview/PageRequestManagerOverview.aspx, specifically the "Partial-Page Update Event Handling" section – Vishal Shah Feb 11 '13 at 16:29