Wednesday, July 22, 2009

Adding Client-Side Script from the Code-Behind Class

All ASP.NET Web pages must be derived directly or indirectly from the Page class in the System.Web.UI namespace. The Page class contains the base set of methods, properties, and events required for a functioning Web page. Among the class's many methods are a few methods designed for injecting client-side script into the rendered HTML. These methods are called from the code-behind class and can therefore be used to emit data-driven client-side script. The pertinent Page class methods for emitting client-side script follow.

The base class is derived from the System.Web.UI.Page class, so you can access the Page class's public methods by calling them directly from your code-behind class.
Note To access the Page class's methods, you can either type in the method name directly, or utilize IntelliSense in Microsoft Visual Studio .NET by entering MyBase. (for Microsoft Visual Basic .NET), this. (for C#), or Page. (for either C# or Visual Basic .NET). If you are using Visual Basic .NET as your programming language of choice, be sure to configure Visual Studio .NET to not hide advanced members, or you won't see these client-side script methods. (To show advanced members, go to Tools | Options | Text Editor | Basic and uncheck Hide advanced members.)

RegisterClientScriptBlock(key, script)

The RegisterClientScriptBlock method adds a block of client-side script after the Web Form's rendered form element, before any Web controls contained within the Web Form. The key input parameter allows you to specify a unique key associated with this script block, whereas the script parameter includes the complete script code to emit. (This script parameter should include the actual script element, along with the client-side JavaScript or Microsoft VBScript.)

When emitting client-side script through the code-behind class of an ASP.NET Web page, typically the value of the key parameter isn't of paramount importance. Simply choose a descriptive key value. The key parameter is more pertinent when injecting client-side script code through a custom, compiled server control. There may be instances where a compiled control requires that there be a set of client-side functions. Multiple instances of the server control on one page might be able to share these common client-side script functions, so these functions need only be emitted once for the entire page, and not once per control instance. For example, the validation controls utilize client-side code to enhance the user experience. This client-side code must be present if there are any validation controls on the page, but if there are multiple validation controls, all can use this single set of shared functions.
By giving a script block a key, a control developer building a control that utilizes a set of common client-side functions can check to see if the required set of common functions has already been added by another instance of the control on the page. If so, it need not re-add the common script. To check if a script block has been added with the same key, use the IsClientScriptBlockRegistered(key) method, which will return a Boolean value indicating whether or not a script block with the same key has been registered. Realize that you can add a script block without first checking if it's registered. If you attempt to add a script block with a key that's already registered, the added script block will be ignored and the original script block will remain assigned to that key.

Note The IsClientScriptBlockRegistered method is particularly useful in two situations. First, it comes in handy when you're adding similar, but unique script blocks, and you need to insure that each script block is given a unique key. The code we'll examine later on in this article illustrates the utility of the "is registered" method. A second use is when building a control that needs some common script, especially if the script is not trivially generated. By using the IsClientScriptBlockRegistered method, you can ensure that the script common to all instances of the server control on the page is generated only once per page load, rather than once per control instance on the page.


The RegisterClientScriptBlock method is useful for adding client-side script that does not rely on any of the form fields present within the Web Form. A common use of this method is to display a client-side alert box. For example, imagine that you had a Web page with some TextBox Web controls and a Save Button. The TextBox controls might have particular values from a database. Imagine that this page allowed the user to modify these values and commit their changes by clicking the Save button. When clicking Save, the Web page would be posted back, and the Button's Click event would fire. You could create a server-side event handler for this event that updates the database. To let the user know that their changes had been saved, you might want to display an alert box that says, "Your changes have been saved." This could be accomplished by adding the following line of code to the Button's Click event handler:


The above will add the specified script content within the page's form, but before the content within the form. When the page is rendered in the user's browser they will see a client-side alert box displayed upon page load.



Note One potentially undesirable side effect of the above example is that the alert box will be displayed right after the browser received the form tag. The browser will suspend rendering of the Web page until the user clicks the alert box's OK button. This means that the user will see a white browser page until they click OK. If you want to have the page displayed completely before displaying the alert box, you can have the JavaScript inserted at the end of the form element using the RegisterStartupScript method, which we'll discuss next.


RegisterStartupScript(key, script)
The RegisterStartupScript method is quite similar to the RegisterClientScriptBlock method. The main difference is the location where the client-side script is emitted. Recall that with the RegisterClientScriptBlock the script is emitted after the start of the form element, but before the form's contents. RegisterStartupScript, on the other hand, adds the specified script at the end of the form, after all form fields. Use RegisterStartupScript to place client-side script that interacts with the rendered HTML elements. (Later we'll look at an example of setting the focus to a form field upon page load; to accomplish this you'll use the RegisterStartupScript method.)
Like RegisterClientScriptBlock, the script blocks added by RegisterStartupScript need a unique key value. Again, this key value is primarily used by custom control developers. Not surprisingly, there is an IsStartupScriptRegistered(key) method as well, which returns a Boolean value indicating if a script block with the specified key has already been registered or not.
Note For more information on using RegisterStartupScript and RegisterClientScriptBlock in creating custom, compiled server controls, read an earlier article of mine: Injecting Client-Side Script from an ASP.NET Server Control.


RegisterArrayDeclaration(arrayName, arrayValue)
If you need to create a client-side JavaScript Array object with some set values, use this method to add a value to a specific array. For example, when using validation controls in an ASP.NET Web page, an Array object (Page_Validators) is built that contains references to the set of validation controls on the page. When the form is submitted, this array is enumerated to check if the various validation controls are valid or not.
To add the values 1, 2, and 3 to a client-side Array object named FavoriteNumbers, you'd use the following server-side code:
RegisterArrayDeclaration("FavoriteNumbers", "1")
RegisterArrayDeclaration("FavoriteNumbers", "2")
RegisterArrayDeclaration("FavoriteNumbers", "3")

This code would emit the following client-side script:

Notice that each array value passed in must be a string; however, the client-side script rendered sets the values of the Array object as the contents of the string. That is, if you wanted to create an Array with the string values "Scott" and "Jisun", you'd use:
RegisterArrayDeclaration("FavoriteFolks", "'Scott'")
RegisterArrayDeclaration("FavoriteFolks ", "'Jisun'")

Notice that the second input parameters are strings that contain 'Scott' and 'Jisun'—text delimited by a single apostrophe. This would render the following client-side script:
var FavoriteFolks = new Array('Scott', 'Jisun');

RegisterHiddenField(hiddenFieldName,hiddenFieldValue)

In classic ASP there was often the need to pass around various bits of information from one page to another. A common way of accomplishing this was using hidden form fields. (A hidden form field is a form field that is not displayed, but whose value is sent on the form's submission. The syntax for creating a hidden form field is .) The need for passing information around by custom hidden form fields in ASP.NET is greatly reduced since the state of the controls in the page is automatically persisted. If, however, you find that you need to create a custom hidden form field, you can do so through the RegisterHiddenField method.
The RegisterHiddenField method accepts two input parameters: the name of the hidden field and the value. For example, to create a hidden form field with the name foo and the value bar, use the following code:
RegisterHiddenField("foo", "bar")

This would add a hidden form field within the page's form element, like so:

No comments:

Post a Comment