Partilhar via


Client Script in ASP.NET Web Pages

ASP.NET is a server-based technology, and therefore does not directly interact with the browser. For example, there are no ASP.NET methods to get keyboard input from the browser, respond to mouse events, or perform other tasks that involve user interaction with the browser. ASP.NET can get the results of such actions after the page has been posted, but cannot directly respond to browser actions.

These types of browser-interaction tasks are best handled using client script written in ECMAScript (JavaScript or JScript). Client script running in the browser can respond immediately to user actions. For example, using client script, you can create "rollover" effects to change a button or a menu item as the user passes the mouse pointer over it. Similarly, you can use client script to check keyboard entry in a text box character by character, change the appearance of the page dynamically, or perform any other task that is primarily oriented to the user interface (UI) and that requires immediate response.

ASP.NET Server Controls and Client Script

A few 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.

Including Your Own Client Script in ASP.NET Pages

Because ASP.NET Web pages are ultimately just Web pages, 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. For example, if your ASP.NET Web page is running in Microsoft Internet Explorer or Mozilla, you can add client script to a page that uses dynamic HTML to manipulate any element on the page. 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.

Your pages can include client script in the same way that any HTML (or other markup) pages can. You can add script blocks to the page to manipulate elements in the 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 and raise all the client-side events that they would in an HTML page.

Working with client script in ASP.NET Web pages differs from working in an HTML page in these areas:

  • Adding client script event handling to ASP.NET server controls.

  • Referencing server controls from client script.

  • Adding client script to the page dynamically.

  • Raising client click events for server controls.

  • Sharing information between client script and server code.

  • Calling server code from client script without postback.

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 depends on the markup language for the page, whether HTML, XHTML, or another language). You can therefore add client-script event handling to controls as you would with any elements on the page. In some cases, however, you must be aware of how the control renders its output and what attributes the control reserves for itself.

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

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

If you include an attribute that does not map to a property of the control, ASP.NET ignores the attribute during server processing and passes it as-is on the markup 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 will be passed through to the browser. This behavior allows 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:

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.

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

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

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

Note that the language you use for server code (Visual Basic or C#) has no effect on client script, which is always written in ECMAScript.

For details, 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 using server code. This is useful if the value of the attribute to add is dynamic. For details, see How to: Set HTML Attributes for Controls in ASP.NET Web Pages.

Identifying Server Controls in Client Script

When an ASP.NET server control is rendered, the control's ClientID property is rendered to the page as both the id attribute and the name 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:

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.

<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 look like the following:

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

The form element renders only an ID attribute, not a name attribute.

You can therefore reference the server control in client script using these attributes. You must typically address the control 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 using syntax as shown in the following code example.

document.forms[0].TextBox1.value = "New value";

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

The exact syntax required to reference a server control depends on what control you are using and whether it is a child of another control. If you are not sure how to reference a control, it can be helpful to run the page, view its source, and determine how the control has been rendered.

Referencing Controls Rendered Inside Other Controls

Some controls render child controls into the page. This includes data list controls such as the GridView, DetailsView, FormView, DataList and Repeater controls, as well as user controls and Web Parts controls.

In these cases, the child controls might not have unique IDs, either because the child controls are defined in a template that generates new control instances for every data row (data list controls), or because the parent control can be added to the page from an external source (user controls and Web Parts controls). These parent controls are therefore naming containers (that is, they implement INamingContainer). A naming container guarantees that its child controls have unique IDs on the page.

For example, you might create an ItemTemplate property in the DataList control and add a CheckBox control whose ID you set to checkEnabled. When the DataList control is rendered, a new checkEnabled control is rendered for each data item. The rendered page must not contain multiple instances of an element named checkEnabled, so the DataList control creates a unique identity for each of its child controls.

Unique identities for child controls of a naming container are generated by rendering two properties. For each child control:

  • The control's UniqueID property is rendered as the name attribute.

  • The control's ClientID property is rendered as the id attribute.

Both the ClientID and UniqueID properties are based on the original ID property, amended with enough information to guarantee that the result is unique in the page. The value of ClientID—that is, of the id attribute in the rendered element—can be referenced in client script.

If you display a page with a naming container in your browser, you can view the page's source to see the unique IDs generated as the name and id attributes for the naming container's child controls. However, it is recommended that you do not rely on directly referencing the IDs as you see them in the browser. The formula used to generate unique IDs for child controls can change. Instead, get the value of the child control's ClientID property and use that value to reference the child control. For example, you might create client script dynamically in your page. If your client script references a child control, get the child control's ClientID property and build it into your dynamic script.

Adding Client Script to a Page Dynamically

In many cases, you can create the client script for your page declaratively, usually as a script block. However, at times you might want to create client script dynamically. This is useful if the script, or values in it, depends on information that is available only on the server. For example, you might inject client script into a page that addresses a server control whose name (ID) is not known until the application runs.

You can also inject a client script include statement that references a file. This is useful if you keep your client script in .js files rather than in the pages themselves, and can be particularly useful if your application is being used with browsers that do not allow script directly.

You can inject client script or a client script include statement into a page by calling methods of the ClientScriptManager class, such as RegisterClientScriptBlock and RegisterStartupScript. For details, see How to: Add Client Script Dynamically to ASP.NET Web Pages.

For all the methods, you provide a type with which the script block is associated and you give the script block a key. Providing a type helps avoid collisions if both a page and any 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 you provide help avoid unnecessary duplication, so you generally do not need 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:

Raising Client Click Events for Server Controls

As noted earlier in this topic, 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.

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!" />

Sharing Information Between Client Script and Server Code

As a rule, client script and server code cannot directly communicate. For example, a client script function cannot pass a value directly to server code during a postback event.

NoteNote

Client script can call server code directly if you implement client callbacks. For details, see Implementing Client Callbacks Without Postbacks in ASP.NET Web Pages.

However, you can have client script and server code interact indirectly. One way is to add a HiddenField control to the page. You can then reference the hidden field in client script by its ID, and also in server code, storing values in either code block and reading them in the other. To pass information from server code to client script, you can create a hidden field programmatically using the RegisterHiddenField method. This method allows you to specify an ID and value for the field, which allows you to store dynamic values in the page in a way that client script can read them.

You can also share values between server code and client code using cookies. For details about writing and reading cookies in server code, see How to: Write a Cookie and How to: Read a Cookie.

Calling Server Code from Client Script Without Postback

In the usual sequence for ASP.NET Web pages, each user action that runs server code requires a postback. However, you can also write code that implements a client callback. In this scenario, client script sends a request to the server to execute a page without performing a complete postback cycle. The page can run a method and return the results of the method to a client function in the browser. A client callback is useful when you want to retain client state such as local variables while getting information from the server.

For details, see Implementing Client Callbacks Without Postbacks in ASP.NET Web Pages.

See Also

Concepts

ASP.NET Web Server Controls and Browser Capabilities
ASP.NET Web Server Control Event Model