简体   繁体   English

OnClick和OnClientClick的操作顺序相反吗?

[英]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. 我有一些想在单击按钮时运行的简单javascript,但是我还希望在服务器上进行一些回发操作。 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. 但是...如果我调用window.close(),则不会发生回发并且不会调用按钮处理程序。 But obviously OnClientClick is called before the postback happens. 但是很明显,OnClientClick是在回发发生之前调用的。 Am I going to have to emit this javascript in the button handler and run it when the page loads after postback? 我是否必须在按钮处理程序中发出此javascript并在回发后页面加载时运行它? If so, what is the proper way to do this these days for ASP.NET 2.0? 如果是这样的话,如今对于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: 使用ClientScript对象中的RegisterStartupScript在回发后运行代码:

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. 为了避免这种情况,您必须执行一些操作,例如在父页面中调用一个函数,该函数可以执行回发以更新页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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