Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

c# - Why can't you UnRegisterStartupScript?

Seems to me it is a bit wierd that you can do..

Page.ClientScript.RegisterStartupScript(this.GetType(), "KeyName", "alert('changed my mind')", true);

And then later on you can't unregister or stop the javascript from being rendered programatically.

Why would Microsoft do this?

I don't like the work around here.. http://hemant-vikram.blogspot.com/2005/11/unregister-startup-script-workaround.html

And I don't like the option of just re-registering it and having it do nothing..

Thoughts?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's actually worse than you think - "just re-registering it and having it do nothing" isn't an option either. The register method checks if a script is already registered with that key, and does nothing if it is. Once you call RegisterStartupScript, nothing you can do will stop that script being rendered.

As to why Microsoft did that, I'd guess that the possibility of changing or removing registered scripts was simply forgotten when RegisterStartupScript was first designed. The design choices happened to make it non-trivial to go back and create an unregister method, so they'd now need a good reason to do that.

When you register a script, it's stored in two places within the ClientScriptManager. A ListDictionary allows checks for whether a script is already registered, and an ArrayList stores the actual scripts as they will be rendered. I assume that the ArrayList is used to ensure that scripts are rendered in the order in which they were registered, but it also means that you can't tell which string in the ArrayList belongs to which key.

It wouldn't be terribly hard to equip your own page class with methods for MaybeAddStartupScript(key,script) and ChangedMyMindAboutThatStartupScript(key). Store the keys and scripts in your own dictionary and then in PreRender, register whichever scripts made it this far. It's certainly annoying to have to do it yourself, though.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...