There are two flavors of client-side script:
- Functions and code that runs immediately - such code is placed within <script> blocks on a page.
- Code that runs in response to some event - this code can be wired up to an HTML element's event handler (i.e., <input type=“button“ onclick=“alert('foo');“ ... />) or specified in code, like window.onload = somefunction.
In ASP.NET 1.x there exist a handful of methods for emiting script in <script> blocks: RegisterClientScriptBlock(), RegisterStartupScript(), RegisterArrayDeclaration(), and so on. For tying script to an HTML element's event handler, Web controls expose an Attributes collection for this purpose (myButton.Attributes[“onclick“] = “alert('foo');“;, for example). For much more on this topic check out my article Working with Client-Side Script.
I recently started digging into ASP.NET 2.0 in earnest, as I blogged about before. The ASP.NET team has added some great improvements to the client-side scripting capabilities of ASP.NET in ASP.NET 2.0. For one, they moved the RegisterXXX() methods out of the Page class and into a ClientScriptManager class, with the RegisterXXX() methods being static. This ClientScriptManager class is exposed as an instance through the Page class's ClientScript property, meaning your ASP.NET code now looks like:
As opposed to:
(Although the old syntax will work for backwards compatibility, but VS 2005 will give you a warning...)
The method signature of the RegisterXXX() methods have changed, too. In ASP.NET 1.x they took in two string parameters, a key and the actual script to emit. In ASP.NET 2.0 they also take in a Type instance, which in most cases will just be set to the type of the control injecting the script. This allows for two different controls to inject script blocks with the same key without overriding one another's scripts. There's also an optional final Boolean parameter that, if set to True, will automatically add the opening and closing <script> block tags.
A number of Web controls have also received some script-related upgrades. The Button/LinkButton/ImageButton controls now have a OnClientClick property, which is basically a shortcut for Attributes[”onclick”], allowing you to do:
myButton.OnClientClick = “alert('foo');”;
All controls also have a Focus() method that injects a bit of script to give focus to the control on document load.
In fact, I whipped up a little demo for a talk I'll be doing later on in the year. You can download the code sample here.