简体   繁体   中英

Reverse order of operations for OnClick and OnClientClick?

I have some simple javascript that I'd like to run when a button is clicked, but I also want some postback action to occur on the server. The logical code for this looks like this:

<asp:Button ID="btnOK" runat="server" Text="Save Changes" OnClientClick="UpdateParent();" OnClick="btnOK_Click" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClientClick="window.close();" />

<script language="javascript" type="text/javascript">
    function UpdateParent()
    {
    window.opener.document.location.reload(true); // or should we postback instead?
    window.close();     
    }
</script>

Basically, a popup window should refresh its parent and then close itself. However... if I call window.close(), the postback does not occur and the button handler is not called. But obviously OnClientClick is called before the postback happens. Am I going to have to emit this javascript in the button handler and run it when the page loads after postback? If so, what is the proper way to do this these days for ASP.NET 2.0?

It's a shame that the code above doesn't work as it's elegantly simple and straightforward.

You have to do the postback before closing the window. Also you want to do the postback before refreshing the parent window, as I guess that the reason to refresh the window is to display the information that you are about to save.

Use the RegisterStartupScript in the ClientScript object to run the code after postback:

Page.ClientScript.RegisterStartupScript(this.GetType(), "close", "window.opener.location.reload(true);window.close();", true);

However, if the parent page is a result of a postback, this would cause a dialog window in the browser informing the user that a post request is needed to reload the page. To avoid this you would have to do something like calling a function in the parent page that could do a postback to update the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM