你为什么不能UnRegisterStartupScript?

Lee*_*one 9 javascript c# asp.net clientscript

在我看来你可以做的有点奇怪..

Page.ClientScript.RegisterStartupScript(this.GetType(), "KeyName", "alert('changed my mind')", true);
Run Code Online (Sandbox Code Playgroud)

然后,您无法取消注册或停止以编程方式呈现javascript.

为什么微软会这样做?

我不喜欢这里的工作.. http://hemant-vikram.blogspot.com/2005/11/unregister-startup-script-workaround.html

而且我不喜欢只是重新注册它并让它什么都不做的选择.

思考?

ste*_*son 9

它实际上比你想象的还要糟糕 - "只是重新注册并让它无所事事"也不是一种选择.register方法检查脚本是否已经使用该密钥注册,如果是,则不执行任何操作.一旦你打电话RegisterStartupScript,你所能做的就是停止渲染那个剧本.

至于为什么微软这样做,我猜想RegisterStartupScript在最初设计的时候,改变或删除注册脚本的可能性就被遗忘了.设计选择恰好使得返回并创建取消注册方法变得非常重要,因此他们现在需要一个很好的理由来做到这一点.

注册脚本时,它存储在ClientScriptManager中的两个位置.ListDictionary允许检查脚本是否已经注册,并且ArrayList存储将呈现的实际脚本.我假设ArrayList用于确保脚本按照它们的注册顺序呈现,但这也意味着您无法分辨ArrayList中的哪个字符串属于哪个键.

它不会是太难与方法来装备自己的页面类MaybeAddStartupScript(key,script)ChangedMyMindAboutThatStartupScript(key).将密钥和脚本存储在您自己的字典中,然后在PreRender中,注册到目前为止的任何脚本.但是,必须自己做这件事当然很烦人.

  • 我从这个答案中得到的关键点是在Pre_Render中注册脚本而不是在Page_Load中注册,然后尝试根据页面上的事件重新注册. (3认同)

Jos*_*dan 5

我假设您想要在某些条件下"取消注册"脚本(已经注册),如下所示:

Page.ClientScript.RegisterStartupScript(this.GetType(), "KeyName", "alert('changed my mind')", true);
...
if(condition)
    Page.ClientScript.UnregisterStartupScript(this.GetType(), "KeyName", "alert('changed my mind')", true);
Run Code Online (Sandbox Code Playgroud)

为什么不能简单地改为:

if(!condition)
    Page.ClientScript.RegisterStartupScript(this.GetType(), "KeyName", "alert('changed my mind')", true);
Run Code Online (Sandbox Code Playgroud)

  • 你是对的而不是通过重构来修复代码味道我正在寻找更快的解决方案..顽皮! (2认同)