Search code examples
javascriptjqueryasp.netfile-uploadupdatepanel

Can I prevent window.onbeforeunload when saving file uploaded to asp:fileupload


I'm setting window.onbeforeunload on aspx page

  <script type="text/javascript">
              window.onbeforeunload = ShowMessage;

              function ShowMessage()
      {   
          alert("Do you want to close?")
      }
</script>

I'm referring a user controls to my aspx page. In my Ascx control, i had one fileupload and asp button.

Once i uploaded a file and clicked on button to save it, before it hitting code behind file, for some reason javascript function ShowMessage() is popping up. Is there any way that I can restrict this from happening. I don't need this message to pop-up when i uploaded file and clicked on Button to save. Please suggest me how to resolve

Ascx.code:

<asp:UpdatePanel ID="upanel" runat="server" UpdateMode="Conditional">
    <Triggers>
        <asp:PostBackTrigger ControlID="btnsave" />
    </Triggers>
    <ContentTemplate>
        <fieldset>
            <p>
                <div id="div1" runat="server" >
                    <asp:FileUpload ID="dcupload" runat="server"  />
                    <asp:Button ID="btnsave" runat="server" Text="Save"  CausesValidation="false" />
                </div>
            </p>
            <asp:Panel ID="UIPanelEnabled" runat="server">
                <asp:GridView ID="gvresults" runat="server" AllowSorting="true" AutoGenerateColumns="false">
                    <Columns>
                    </Columns>
                </asp:GridView>
            </asp:Panel>

    </ContentTemplate>
</asp:UpdatePanel>

Solution

  • You can define a function DisableMessage that resets the onbeforeunload event handler:

    <script type="text/javascript">
        window.onbeforeunload = ShowMessage;
    
        function DisableMessage() {
            window.onbeforeunload = null;
        }
    
        function ShowMessage() {
            return "Do you want to close?";
        }
    </script>
    

    And call that function in the OnClientClick event of the button:

    <asp:Button ID="btnsave" runat="server" OnClientClick="DisableMessage();" ... />
    

    By the way, simply returning a string in ShowMessage (as shown above) allows the onbeforeunload event handler to work in all browsers, which is not the case if you call alert.