Freigeben über


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:

  • Object-oriented programming in JavaScript.

  • Asynchronous postbacks.

  • Application Web services for authentication and profiles.

  • Server controls that manage client script with extended debugging and trace support.

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:

  • Scenarios

  • Including Custom Client Script in ASP.NET Pages

  • Extending JavaScript with ASP.NET AJAX Features

  • ASP.NET Server Controls That Depend on Client Script

  • Adding Client Script Events to ASP.NET Server Controls

  • Referencing Server Controls in Client Script

  • Raising Client Click Events for Server Controls

  • Communicating Between Client Script and Server Code

  • Creating Client Script Components

  • Adding Client Functionality to Server Controls

Scenarios

Use client script when you want to do the following:

  • 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:

    • Reduce full-page refreshes and avoid page flicker by manipulating DOM elements dynamically on the page.

    • 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.

Including Custom Client Script in ASP.NET Pages

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.

Including Static Client Script Blocks

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.

Note

You can reference ASP.NET server controls in client script. For more information, see Referencing Server Controls in Client Script later in this topic.

An ASP.NET Web page can also access a script file by referring to it in the src attribute of a <script> tag, as in the following example:

<script type="text/javascript" src="MyScript.js"></script>

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.

Creating Client Script Dynamically

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.

  • It adds a client event to the TextBox control.

  • It generates the span element.

The code assumes that the page contains a check box named checkDisplayCount whose AutoPostBack property is set to true and a PlaceHolder control named PlaceHolder1.

Protected Sub Page_Load(ByVal sender As Object, _
        ByVal e As System.EventArgs)
    If checkDisplayCount.Checked Then
        Dim scriptText As String = ""
        scriptText &= "function DisplayCharCount(){"
        scriptText &= "   getElementByID("spanCounter").innerText = " & _
            "document.forms[0].TextBox1.value.length"
        scriptText &= "}"
        ClientScriptManager.RegisterClientScriptBlock(Me.GetType(), _
            "CounterScript", scriptText, True)
        TextBox1.Attributes.Add("onkeyup", "DisplayCharCount()")
        Dim spanLiteral As New LiteralControl()
        spanLiteral.Text = "<span id=""spanCounter""></span>"
        PlaceHolder1.Controls.Add(spanLiteral)
    End If
End Sub
void Page_Load(object sender, EventArgs e)
{
    if(checkDisplayCount.Checked)
    {
        String scriptText = "";
        scriptText += "function DisplayCharCount(){";
        scriptText += "   spanCounter.innerText = " + 
            " document.forms[0].TextBox1.value.length";
        scriptText += "}";
        ClientScriptManager.RegisterClientScriptBlock(this.GetType(), 
           "CounterScript", scriptText, true);
        TextBox1.Attributes.Add("onkeyup", "DisplayCharCount()");
        LiteralControl spanLiteral = new 
            LiteralControl("<span id=\"spanCounter\"></span>");
        PlaceHolder1.Controls.Add(spanLiteral);
    }
}

For more information, see How to: Add Client Script Dynamically to ASP.NET Web Pages.

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:

Adding Client Script by Using the ScriptManager Control

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.

For an overview of the ScriptManager control, see ScriptManager Control Overview. For information about how to embed a JavaScript file as a resource in an assembly and how to consume it in a Web page, see Walkthrough: Embedding a JavaScript File as a Resource in an Assembly.

Note

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.

Extending JavaScript with ASP.NET AJAX Features

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:

AJAX Features Browser Compatibility

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.

ASP.NET Server Controls That Depend on Client Script

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.

For more information, see ASP.NET Web Server Controls That Use Client Script.

Adding Client Script Events to ASP.NET Server Controls

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.

For more information, see How to: Add Client Script Events to ASP.NET Web Server Controls

Adding Client Event Handlers Declaratively

In the markup for ASP.NET server controls, you set property values by using attributes. For example, to set the Text property of a TextBox control, you can create markup like the following:

<asp:textbox id="TextBox1" runat="server" text="Sample Text" />
Security noteSecurity Note

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:

<asp:textbox id="TextBox1" runat="server" text="Sample Text" 
  onkeyup="spanCounter.innerText=this.value.length;" />

Alternatively, the event could call a method that is defined in client script elsewhere in the page:

<asp:textbox id="TextBox1" runat="server" text="Sample Text" 
  onkeyup="DisplayCount(this);" />

Note that the language that you use for server code (Visual Basic or C#) does not affect client script, which is always written in ECMAScript (JavaScript or JScript).

For more information, see How to: Add Client Script Events to ASP.NET Web Server Controls.

Adding Attributes in Server Code

In addition to adding pass-through attributes to a control declaratively, you can add attributes programmatically by using server code. This is useful if the value of the attribute to add is known only at run time. For details, see How to: Set HTML Attributes for Controls in ASP.NET Web Pages.

Referencing Server Controls in Client Script

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:

<asp:textbox id="TextBox1" runat="server" text="Sample Text" />

The ClientID property is set to TextBox1, and the resulting element in an HTML-based browser would resemble the following:

<input name="TextBox1" type="text" value="Sample Text" id="TextBox1" />

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:

var tb1 = document.getElementById("TextBox1");
tb1.value = "New value";

The following example assumes that the form element on the page has had its id attribute set to form1.

document.form1.TextBox1.value = "New value";

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:

Raising Client Click Events for Server Controls

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:

<asp:button id="Button1" 
  runat="server" 
  OnClientClick="return confirm('Ok to post?')" 
  onclick="Button1_Click" 
  Text="Click!" />

Communicating Between Client Script and Server Code

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.

Calling Server Code Directly from Client Script

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.

  • Implement a client callback. In this scenario, you write the client code that sends the request and that processes the result. The most common approach is to create a calling function in client script and a callback function that is invoked when the server returns the results. For more information, see Implementing Client Callbacks Programmatically Without Postbacks in ASP.NET Web Pages

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.

Sharing Data by Using a HiddenField Control

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.

Sharing Data by Using Cookies

You can also share values between server code and client code by using cookies. For details about how to write and read cookies in server code, see How to: Write a Cookie and How to: Read a Cookie. For details about how to use JavaScript to read and write cookies, see JavaScript and cookies on the MSDN Web site.

Sharing Data During Asynchronous Postbacks

If you are using AJAX features of ASP.NET, you can send custom data as a string from the server to the client during asynchronous postbacks (partial page rendering) by using the RegisterDataItem method. The RegisterDataItem method enables you to use server code to register a field that is attached to a control. You can access the field's value in client script in the browser through the ASP.NET AJAX Sys.WebForms.PageLoadingEventArgs and Sys.WebForms.PageLoadedEventArgs objects. The RegisterDataItem method can be called only during an asynchronous postback.

For information about how to use the RegisterDataItem method to share data between the server and the client, see the following topics:

Creating Client Script Components

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.

For more information, see the following topics:

Adding Client Functionality to Server Controls

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.

For more information, see the following topics:

See Also

Concepts

ASP.NET Client Script

ASP.NET Web Server Controls and Browser Capabilities

ASP.NET Web Forms Server Control Event Model

ASP.NET Web Server Control Identification