Sep
10
2006
System.Web.UI.Page.RegisterStartupScript(string,string) is obsolete
Posted by admin under
ASP.NET 2.0

I bet you use the RegisterStartupScript a lot - in conjunction with IsClientScriptBlockRegistered it is an easy way to insert a chunk of Javascript code into your ASP.NET page.
if ( !Page.IsStartupScriptRegistered("mytest") )
Page.RegisterStartupScript("myrest", "<script>alert('Hello');</script>");
However, in ASP.NET 2.0 it gives you an error - or more correctly warnings telling you that both functions are obsolete.
'System.Web.UI.Page.IsStartupScriptRegistered(string)' is obsolete: 'The recommended alternative is ClientScript.IsStartupScriptRegistered(string key).
'System.Web.UI.Page.RegisterStartupScript(string, string)' is obsolete: 'The recommended alternative is ClientScript.RegisterStartupScript(Type type, string key, string script).
Ok, fine. Lets try to replace it with the new alternatives instead. As for the ScriptRegistered stuff, no problem. It takes the same parameter and therefore just replace the call with ClientScript.IsStartupScriptRegistered.
But what about ClientScript.RegisterStartupScript. Here we have an extra parameter: Type type.
In the docs it just says "The type of the startup script to register. ". Makes not much sense, but my guess it the reason for it is to enable for controls to be able to inject scripts into the site without being afraid of name collisions.
I.e now Control 1 from Vendor 1 can use
ClientScript.RegisterStartupScript( typeof(Vendor1.SuperControl1), "startscript", "<script>...some javascript code...;</script>");
and independent from that Control 2 from Vendor 2 can use
ClientScript.RegisterStartupScript( typeof(Vendor2.HelloControl), "startscript", "<script>...some javascript code...;</script>");
I.e the uniqueness for keys for the scripts are determined by one extra factor - a type as well.
Anyway, for most of the time, when you are creating JavaScript directly from your page instead of from within controls, typeof(Page) will be fine.
if (!ClientScript.IsStartupScriptRegistered("mytest"))
ClientScript.RegisterStartupScript( typeof(Page), "myrest", "<script>alert('Hello');</script>");