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

The power of injecting JavaScript into your ASP.NET pages from your codebehind code is really important, considering that the controls client ID:s will not be the same as in your designtime ASPX file.
In ASP.NET 1.1 it was pretty easy to inject JavaScript by using this code
if ( !Page.IsClientScriptBlockRegistered("mytest") )
Page.RegisterClientScriptBlock("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.IsClientScriptBlockRegistered(string)' is obsolete: 'The recommended alternative is ClientScript.IsClientScriptBlockRegistered(string key).
'System.Web.UI.Page.RegisterClientScriptBlock(string, string)' is obsolete: 'The recommended alternative is ClientScript.RegisterClientScriptBlock(Type type, string key, string script).
Ok, fine. Lets try to replace it with the new alternatives instead. As for the IsClientScriptBlockRegistered stuff, no problem. It takes the same parameter and therefore we cann just replace the call with ClientScript.IsClientScriptBlockRegistered.
But what about ClientScript.RegisterClientScriptBlock? 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.RegisterClientScriptBlock( typeof(Vendor1.SuperControl1), "startscript", "<script>...some javascript code...;</script>");
and independent from that Control 2 from Vendor 2 can use
ClientScript.RegisterClientScriptBlock( 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.IsClientScriptBlockRegistered("mytest"))
ClientScript.RegisterClientScriptBlock( typeof(Page), "myrest", "<script>alert('Hello');</script>");