多次注册脚本 [英] Registering a script multiple times

查看:87
本文介绍了多次注册脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在后面的代码中,我注册了一个启动脚本,如下所示:

In the code behind, I register a startup script as below:

  string strFunctionName = "ShouldAdd";
  sb.Append(strFunctionName + @"((blnShouldAdd ? "true" : "false") + ", true);");

  ScriptManager.RegisterStartupScript(this, this.GetType(), "shouldAdd", sb.ToString(), true);

这段代码被调用两次,一次是在 blnShouldAdd 评估为 false 时在页面加载中,一次是在 blnShouldAdd 时在按钮的事件处理程序中.>的值为 true .

This piece of code is called twice, once in Page Load when blnShouldAdd evaluates to false and in the event handler of a button when blnShouldAdd evaluates to true.

奇怪的是,当我调试代码并进入Shouldsho JS函数时,该值始终为false.我认为它是正确的,因为事件处理程序中的第二个调用会覆盖第一个调用.

Strangely, when I debug the code and step into the ShouldAdd JS function, the value is always false. I would assume it to be true as the second call in the event handler overrides the first one.

有什么想法吗?

推荐答案

单击按钮也将运行页面加载,这是asp.net页面生命周期的一部分,并且它在按钮的事件处理程序之前运行.因此,当您到达按钮的事件处理程序时,您已经在Page Load中注册了脚本,因此注册具有相同(类型,键)对的另一个脚本的请求将被忽略.

Page Load also runs when you click the button, as part of the asp.net page lifecycle, and it runs before the button's event handler. So, when you reach the button's event handler you already registered the script in Page Load, so the request to register another script with the same (type, key) pair is ignored.

也许您应该将呼叫从页面加载"移到pag生命周期的后期,也许是将PreRender放在更好的位置.

Maybe you should move the call from Page Load to a later point of the pag lifecycle, maybe PreRender in a better place.

这篇关于多次注册脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆