Knowledge2Share Knowledge2Share - 1 year ago 95
ASP.NET (C#) Question

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?")

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


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


Answer Source

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?";

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download