Client Script in ASP.NET Web Pages

ASP.NET Web applications are not limited to server-based tools and languages. You can include ECMAScript (JavaScript or JScript) in your ASP.NET Web pages to create rich browser-based functionality. A wide range of features for client script support is available in ASP.NET.

One option is to create and add individual snippets of client script to ASP.NET Web pages to support browser behavior that you design for your application. This option is practical if you want to include only a few small pieces of JavaScript code or if you are working with JavaScript code that you already have. This option also helps keep the size of your ASP.NET Web pages to a minimum.

Alternatively, you can take advantage of the powerful AJAX features of ASP.NET. These AJAX features include a complete framework that supports the following:

Using ASP.NET AJAX features lets you take advantage of JavaScript functionality with less manual coding. It provides extended JavaScript functionality, and it provides a framework for creating client functionality that is integrated into ASP.NET.

This topic provides an overview of options for adding client script to ASP.NET Web pages. It contains the following sections:

Improve the user experience with Web pages that are richer, that are more responsive to user actions, and that behave like traditional client applications. For example, you can use client script to check keyboard entry in a text box as each character is typed.

Add AJAX functionality to ASP.NET Web pages, which enables you to do the following:

Update and manage the user interface (UI) without a requiring a postback to the server.

Organize your code into client components. Client components are reusable objects that encapsulate JavaScript that is based on the Microsoft Ajax Library. Client components can also be managed by custom server side controls or associated with existing server controls to add client functionality.

Because ASP.NET Web pages just render HTML markup, you can add your own client script to ASP.NET pages. Client script is supported in ASP.NET pages to the extent that the browser requesting the page supports client script. If the page is running in a browser on a mobile phone or other device, the degree of support for client script varies, depending on the browser.

There are several options for including client script in ASP.NET pages:

You can include client script statically in a script block that includes code or that uses an include attribute to reference a JavaScript (.js) file. Use this option to insert script blocks or JavaScript files contain client script that you do not have to create dynamically, and that do not require additional AJAX functionality provided by the Microsoft Ajax Library.

You can dynamically create and add client script to ASP.NET Web page by using the ClientScriptManager class. Use this option when you want to create scripts that depend on information that is available only at run time.

If you plan to take advantage of the AJAX features of ASP.NET, you can manage client-script files by using the ScriptManager server control. The ScriptManager server control also ensures that the Microsoft Ajax Library is loaded on the browser before your scripts run. For more information, see Microsoft Ajax Overview.

You can add script blocks to an ASP.NET page just as you would for any HTML page. You can use client script to write event handlers for client events such as the page's onload event. When an ASP.NET page is running in the browser, the markup elements on the page are addressable in client script. They raise all the client events that they do in an HTML page.

Keeping client script in external .js files rather than in the pages themselves can help organize your client scripts. It can also make them easier to manage for version control and easier to share between pages.

External .js files are cached by the browser, similar to the way Web pages and images are cached. After the script has been loaded by the browser as an external file, it is available in the cache to any other Web page that requires it. This can help increase the performance of the Web application.

In many cases, you can create the client script for your page declaratively, usually as a script block. However, you can also create client script dynamically. This is useful if the script depends on information that is available only at run time. For example, you might insert client script into a page that addresses a server control whose name (ID) is not known until the application runs, or you might create script that depends on values that you get from a user.

You can create and insert client script dynamically into a rendered page by calling methods of the ClientScriptManager class, such as the following:

The following example shows how to add dynamically generated client script to the page. The code checks whether a check box named checkDisplayCount is selected. If so, the code performs the following tasks:

It creates a client script function that uses a span element to display the character count in a TextBox control named TextBox1.

For ClientScriptManager class methods, you provide a type that the script block is associated with and you give the script block a key. Providing a type helps avoid collisions if both a page and controls (custom controls or user controls) add script blocks into the same page. Using a key helps avoid duplication. If you call one of the methods to add script, and a script with the same key and the same type already exists, the script is not added again.

The type and key that you provide help avoid unnecessary duplication. Therefore, you generally do not have to determine explicitly whether a script block already exists. However, if it is useful in your application to check for an existing script block, you can call the following methods:

If you are using ASP.NET AJAX features, the ScriptManager control provides a way for you to add script files in a page. This includes static script files (.js files) on disk and script files that are embedded as resources in an assembly. You can specify script files declaratively in the control. Alternatively, you can use registration methods of the ScriptManager control that let you manage existing client script files programmatically and that let you work with scripts for partial-page update support.

If you are using client AJAX features of ASP.NET but not server-based features, use methods of the ClientScriptManager class to insert scripts in an ASP.NET Web page. For example, if you are not using the UpdatePanel control or localization features for scripts, you do not need the ScriptManager control. Therefore, you cannot call its methods to insert client script into the page. Using methods of the ClientScriptManager class is usually more efficient than using ScriptManager control methods. This is because ClientScriptManager class methods do not require the extra processing for server-based features that are supported by the ScriptManager control. If you must create script dynamically (instead of simply managing existing script), use the ClientScriptManager class to insert client script into a page. For example, use the ClientScriptManager class if you want to create client script programmatically based on information that a preexisting script file cannot reference.

ASP.NET supports AJAX functionality, which enables you to use client script to add rich features to an ASP.NET Web page. This includes asynchronous postbacks, a very responsive UI, and more. AJAX functionality is implemented by using the Microsoft Ajax Library, which consists of client-script libraries that incorporate cross-browser ECMAScript (JavaScript) and dynamic HTML (DHTML) technologies. AJAX functionality is integrated with the ASP.NET server-based development platform.

You can use the Microsoft Ajax Library type system, object-oriented features, and extensions to JavaScript objects in order to provide the following features for creating custom client script:

Namespaces

Inheritance

Interfaces

Enumerations

Reflection

Debugging helpers

Tracing

Typed exception handling

Helper methods for strings and arrays.

Note

You can use the Microsoft Ajax Library even if you do not intend to use server-based AJAX features of ASP.NET.

For more information about how the Microsoft Ajax Library extends JavaScript, see the following topics:

A browser compatibility layer in the Microsoft Ajax Library provides AJAX scripting compatibility for the most frequently used browsers (including Microsoft Internet Explorer, Mozilla Firefox, and Apple Safari). This enables you to write the same script regardless of which supported browser you are targeting. For more information, see Microsoft Ajax Overview.

Some ASP.NET server controls depend on client script for their functionality. For example, the LinkButton control requires client script to support its postback behavior. The client script required for ASP.NET Web server controls is added automatically to the page when the page is rendered. The client script generated for these controls is independent of any client script that you create yourself.

ASP.NET controls render as elements in the page. (The exact elements rendered by a control depend on the markup language for the page, which might include HTML, XHTML, or another language.) You can therefore add client-script event handling to controls as you would with any elements on the page. However, in some cases you must know how the control renders its output and what attributes the control reserves for itself.

A TextBox accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see Script Exploits Overview.

If you include an attribute that does not map to a property of the control, ASP.NET ignores the attribute during server processing. It passes it as-is as part of the markup that is generated by the control to the browser. For example, the TextBox control has no property named onkeyup. Therefore, if you include an onkeyup attribute in the markup for a TextBox control, the attribute is passed through to the browser. This behavior enables you to add event bindings to server controls by declaring them in the markup. For example, the following markup for a TextBox control causes the text box to display the current text length in a span element named spanCounter any time the user presses a key in the text box:

When an ASP.NET server control is rendered, the control's ClientID property is rendered in the page as the id attribute of the resulting element. (The ClientID property is automatically generated from the ID property that you set.) For example, you might create the following ASP.NET server control:

Therefore, you can reference the server control in client script by using these attributes. You typically address the control by using a fully qualified reference in client script. If the control is a child of the form element in the page, you generally reference the control in client script by using syntax as shown in the following example:

The id attribute that will be generated for a server control depends on what control you are using and whether it is a child of another control. When a control is included inside a repeating control, such as the GridView, ListView, or Repeater control, a single control defined in markup often creates multiple instances of the control in the rendered HTML. The ASP.NET page framework provides a mechanism to make sure that each control in the rendered HTML for a page has a unique ID. For more information about the algorithms ASP.NET uses to assign ClientID values, see the ClientIDMode property and the following topics:

As noted earlier, you can add a client click event to most ASP.NET server controls by adding the onclick attribute to the control's markup. However, some controls reserve the onclick attribute to define binding to the server event. These include the Button, LinkButton, and ImageButton controls. In these controls, you cannot use the onclick attribute declaratively to add a client-script handler to the control.

You can add a client-script handler for the click event in two ways:

Set the control's OnClientClick property to the script to execute. When the button control renders, the OnClientClick value is turned into an onclick attribute.

Add an onclick attribute programmatically by calling the Add method of the control's Attributes collection.

Note

You cannot add an onclick attribute programmatically to a server control if the control already uses onclick as part of its basic functionality, such as the LinkButton.

The following code example shows a Button control that raises both client-side and server Click events:

In addition to using standard postbacks, ASP.NET Web pages can communicate between client script and server code in several ways. AJAX features in ASP.NET such as the UpdatePanel server control automate asynchronous partial-page updates for you. In addition, ASP.NET AJAX supports calling Web services asynchronously.

If you do not use AJAX features of ASP.NET, you can invoke a custom client callback directly and share information between the browser and the server through a variety of methods. The following section provides information about available options.

Client script can call server code directly by implementing a client callback. In a common sequence for ASP.NET Web pages, each user action that runs server code requires a postback. However, you can also invoke server processing from the browser without a full postback. In this scenario, the browser does not send the whole page to the server and then reload it when the server responds. Instead, the browser sends a small amount of data to the server. When the server sends a response, client script in the browser processes the returned data without reloading the page. During the server processing, all client state such as local variables is retained. This process is known as an asynchronous postback and is key to partial-page rendering.

You can call server methods from client script without a postback in these ways:

Use the ASP.NET UpdatePanel server control. This control is part of the AJAX functionality of ASP.NET. It enables you to define a region of a page that will be refreshed with a partial-page update. When you use the UpdatePanel control, you do not have to write any client script yourself to invoke asynchronous partial-page updates. For more information, see Partial-Page Rendering Overview and UpdatePanel Control Overview.

Use ASP.NET AJAX support for Web service communication to write client script that invokes a Web server method. This approach is conceptually similar to writing your own client script callback to call a Web server method. However, the Microsoft Ajax Library handles the details of invoking the server method and provides a more robust client-script library for making and processing the call. For more information, see ASP.NET AJAX Web Services.

Each approach has advantages. Creating your own client callback often gives you the lowest overhead and smallest page size. Using the UpdatePanel server control lets you implement partial-page updates without writing any client script yourself. Using AJAX to call Web services also eliminates most of the client script you would write for making asynchronous Web service calls.

You can share information between client script and server code by adding a HiddenField control to the page. You can reference the hidden field in client script by its ID. You can also reference the hidden field in server code. This enables you to store values in either code block and read them in the other. To pass information from server code to client script, you can create a hidden field programmatically by using the RegisterHiddenField method. This method lets you specify an ID and value for the field. You can use the field to store dynamic values in the page in a way that client script can read them.

Client components are reusable objects that encapsulate JavaScript that is based on the Microsoft Ajax Library. The library provides the following base client object types classes: Component (which is a base class for non-visual components), Control, and Behavior. You can derive from these classes to provide rich client functionality, which includes the following:

Getting access to the life cycle of a component from initialization to disposing. This includes events that are raised when property values change.

Representing a DOM element as a client object that has new functionality. This extends the behavior of DOM elements. For example, you can add watermarking behavior that can be attached to an existing text box.

Any existing or custom ASP.NET server control can be turned into an ASP.NET AJAX extender control. An extender control is a Web server control that uses ECMAScript (JavaScript), DHTML, and AJAX capabilities of the Web browser to add features such as interactivity and asynchronous communication with the server.