[英]How often are the scripts registered with RegisterStartupScript, RegisterScriptBlock etc. executed?
Let's say I have a button which modifies some content inside an update panel:假设我有一个按钮可以修改更新面板中的一些内容:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "New Text";
}
I also want to execute some code on the client side, after the UpdatePanel has been updated.在更新 UpdatePanel 之后,我还想在客户端执行一些代码。 My first idea would be to execute
ScriptManager.RegisterClientScriptBlock
or RegisterStartupScript
:我的第一个想法是执行
ScriptManager.RegisterClientScriptBlock
或RegisterStartupScript
:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "New Text";
var x = getSomeDatabaseQueryResultBasedOn(TextBox1.Text, ...);
ScriptManager.RegisterStartupScript(this, typeof(WebForm1), "SomeKey",
"/* this is my script, using `x` */", true)
}
However, the documentation of RegisterStartupScript says:但是, RegisterStartupScript 的文档说:
You use this method to register a startup script block that is included every time that an asynchronous postback occurs.
您使用此方法注册一个启动脚本块,每次发生异步回发时都会包含该脚本块。
I don't want this code to execute "every time that an asynchronous postback occurs" .我不希望此代码“每次发生异步回发时”执行。 I want it to execute only right now (after control is back with the browser).
我希望它现在只执行(在浏览器返回控制权之后)。 If Button2 is clicked, I don't want any script executed, and if Button1 is clicked again,
x
might be different and I want a new script to be executed.如果单击 Button2,我不想执行任何脚本,如果再次单击 Button1,
x
可能不同,我希望执行新脚本。 Unfortunately, I didn't find a ScriptManager.ExecuteOnce
method.不幸的是,我没有找到
ScriptManager.ExecuteOnce
方法。
Is there such a method?有这样的方法吗? Or did I just misunderstand the documentation of
RegisterStartupScript
?或者我只是误解了
RegisterStartupScript
的文档?
The very next line from that documentation says:该文档的下一行说:
"To register a script block for a control that is inside an UpdatePanel control so that script is registered only when the UpdatePanel control is updated, use the RegisterClientScriptBlock(Control, Type, String, String, Boolean) overload of this method."
“要为 UpdatePanel 控件内的控件注册脚本块,以便仅在更新 UpdatePanel 控件时注册脚本,请使用此方法的 RegisterClientScriptBlock(Control, Type, String, String, Boolean) 重载。”
Is that not what you want?那不是你想要的吗?
When you include the StartupScript duing the async postback, it will only exist in the partial response sent from the server.当您在异步回发期间包含 StartupScript 时,它只会存在于从服务器发送的部分响应中。
If you do something like this:如果你这样做:
if(ScriptManager.IsInAsyncPostBack)
{
myDiv.InnerText = "partial response";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), DateTime.Now.ToString("ssfff"), "alert(0);"), true);
}
Your response will look something like this:您的回复将如下所示:
|blabla|blabla|updatePanel_ctrl00|someparams
<div>partial response</div>
<script> alert(0); </script>
Thus that piece of javascript will execute as soon as the response is received.因此 javascript 将在收到响应后立即执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.