Version 1.x of the Framework has a handful of methods hanging off of the Pageobject to help
with client-side scripting. One of these, for example, is RegisterClientScriptBlock. This
handy method accepts two strings. The first one names the script block; the second is the
actual script you want to inject into the page.
You use this from controls to inject script into the page while avoiding duplicate script
blocks. If more than one instance of a control attempts to inject the same script block, the
runtime is smart enough to inject it only once. From the previous example, you could pull the
populateListB method out into a file named Interdepends.js. From the implementation of
the interdependent lists control, you could add a line of code to include it:
this.RegisterClientScriptBlock(
"Interdepends",
"scripts");
This is a two-fold improvement over the previous example. It gets the script out into its
own file (for easier maintenance and versioning), and it guarantees that the block will be
included in the page only once.
All of the RegisterXYZ methods (see Table 4-2) have been deprecated in version 2.0 of the
Framework. Instead, the page object now carries an instance of the new ClientScriptManager
type, named ClientScript. This centralizes the functionality for managing scripts; you no
longer have a handful of random methods hanging off the page object.
Of course, you must realize that 2.0 attempts to be backwards compatible, so just because
these are deprecated doesn’t mean they go away. They will survive in-perpetuity in the name
of backwards compatibility (or until Microsoft ships a non-backwards compatible version of
ASP.NET), so your existing code will continue to work.
With new development, however, you should use the methods of the client script man-
ager. Let’s take a look at these. The point of a lot of these register methods is first and foremost
to avoid duplicating the code that’s being sent to your page, which can happen easily when a
control is generating code and more than one instance of the control is placed on a single Web
Form. Some of these methods also do a bit of code generation for you, but it’s nothing sub-
stantial.











0 comments:
Post a Comment