Manages ASP.NET AJAX script libraries and script files, partial-page rendering, and client proxy class generation for Web and application services.
Namespace:
System.Web.UI
Assembly:
System.Web.Extensions (in System.Web.Extensions.dll)
Visual Basic (Declaration)
<AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level := AspNetHostingPermissionLevel.Minimal)> _
<AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level := AspNetHostingPermissionLevel.Minimal)> _
Public Class ScriptManager _
Inherits Control _
Implements IPostBackDataHandler, IScriptManager
Dim instance As ScriptManager
[AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public class ScriptManager : Control,
IPostBackDataHandler, IScriptManager
[AspNetHostingPermissionAttribute(SecurityAction::InheritanceDemand, Level = AspNetHostingPermissionLevel::Minimal)]
[AspNetHostingPermissionAttribute(SecurityAction::LinkDemand, Level = AspNetHostingPermissionLevel::Minimal)]
public ref class ScriptManager : public Control,
IPostBackDataHandler, IScriptManager
public class ScriptManager extends Control implements IPostBackDataHandler, IScriptManager
The ScriptManager control is central to AJAX functionality in ASP.NET. The control manages all ASP.NET AJAX resources on a page. This includes downloading Microsoft AJAX Library scripts to the browser and coordinating partial-page updates that are enabled by using UpdatePanel controls. In addition, the ScriptManager control enables you to do the following:
Register script that is compatible with partial-page updates. In order to manage dependencies between your script and the core library, any script that you register is loaded after the Microsoft AJAX Library script.
Specify whether release or debug scripts are sent to the browser.
Provide access to Web service methods from script by registering Web services with the ScriptManager control.
Provide access to ASP.NET authentication, role, and profile application services from client script by registering these services with the ScriptManager control.
Enable culture-specific display of ECMAScript (JavaScript) Date, Number, and String functions in the browser.
Access localization resources for embedded script files or for stand-alone script files by using the ResourceUICultures property of the ScriptReference control.
Register server controls that implement the IExtenderControl or IScriptControl interfaces with the ScriptManager control so that script required by client components and behaviors is rendered.
Partial-Page Rendering
The ability of an ASP.NET page to support partial-page rendering is controlled by the following factors:
You can override the value of the EnablePartialRendering property at run time during or before the page's Init event. If you try to change this property after the page's Init event has occurred, an InvalidOperationException exception is thrown.
When partial-page rendering is supported, the ScriptManager control renders script to enable asynchronous postbacks and partial-page updates. The regions of the page to be updated are designated by using UpdatePanel controls. The ScriptManager control handles the asynchronous postbacks and refreshes only the regions of the page that have to be updated. For more information about partial-page rendering, see Partial-Page Rendering Overview. For more information about the conditions that cause an update, see UpdatePanel Control Overview.
Using the ScriptManager Control with Master Pages, User Controls, and Other Child Components
Script Management and Registration Overview
The ScriptManager control enables you to register script that is then rendered as part of the page. The ScriptManager control registration methods can be broken into the following three categories:
Registration methods that guarantee that script dependencies on the Microsoft AJAX Library are maintained.
Registration methods that are not dependent on the Microsoft AJAX Library, but that are compatible with UpdatePanel controls.
Registration methods that support working with UpdatePanel controls.
For more information about how to create and use AJAX script in ASP.NET, see Creating Custom Client Script by Using the Microsoft AJAX Library.
Registering Script That Is Dependent on the Microsoft AJAX Library
You can use the following methods to register script files in a way that guarantees that any dependencies on the Microsoft AJAX Library are maintained.
Registering Partial-Page Update Compatible Scripts
You can use the following methods to register script files that are not dependent on the Microsoft AJAX Library but that are compatible with UpdatePanel controls. These methods correspond to similar methods of the ClientScriptManager control. If you are rendering script for use inside an UpdatePanel control, make sure that you call the methods of the ScriptManager control.
Method | Definition |
|---|
RegisterArrayDeclaration
| Adds a value to a JavaScript array. If the array does not exist, it is created. |
RegisterClientScriptBlock
| Renders a script element after the page's opening <form> tag. The script is specified as a string parameter. |
RegisterClientScriptInclude
| Renders a script element after the page's opening <form> tag. The script content is specified by setting the src attribute to a URL that points to a script file. |
RegisterClientScriptResource
| Renders a script element after the page's opening <form> tag. The script content is specified with a resource name in an assembly. The src attribute is automatically populated with a URL by a call to an HTTP handler that retrieves the named script from the assembly. |
RegisterExpandoAttribute
| Renders a custom name/value attribute pair (an expando) in the markup for a specified control. |
RegisterHiddenField
| Renders a hidden field. |
RegisterOnSubmitStatement
| Registers a script that is executed in response to the form element's submit event. The onSubmit attribute references the specified script. |
RegisterStartupScript
| Renders a startup script block just before the page's closing </form> tag. The script to render is specified as a string parameter. |
When you register methods, you specify a type/key pair for that script. If a script with the same type/key pair is already registered, a new script is not registered. Similarly, if you register a script with a type/resource name pair that already exists, the script element that references the resource is not added again. When you register an expando attribute of a previously registered attribute, an exception is thrown. Duplicate registration of array values is allowed.
When you call the RegisterClientScriptInclude or the RegisterClientScriptResource method, avoid registering script that executes inline functions. Instead, register script that contains function definitions like event handlers or custom class definitions for your application.
Registration Methods for UpdatePanel Controls
You can use the following methods to customize partial-page updates when you use UpdatePanel controls.
Method | Definition |
|---|
RegisterAsyncPostBackControl
| Registers a control as a trigger for asynchronous postbacks. |
RegisterDataItem
| Sends custom data to controls during partial-page rendering. |
RegisterDispose
| Registers a dispose script for a control that is inside an UpdatePanel control. The script is executed when the UpdatePanel control is updated or deleted. The dispose method is used for client components that are part of the Microsoft AJAX Library and that have to free resources when a component is no longer used. |
RegisterPostBackControl
| Registers a control as a trigger for a full postback. This method is used for controls inside an UpdatePanel control that would otherwise perform asynchronous postbacks. |
Web Service References
Localization
The ScriptManager control generates references in the rendered page that point to the appropriate localized script files, which are either script files embedded in assemblies or stand-alone script files.
When the EnableScriptLocalization property is set to true, the ScriptManager control retrieves localized resources (such as localized strings) for the current culture, if they exist. The ScriptManager control provides the following functionality for using localized resources:
Script files that are embedded in an assembly. The ScriptManager control determines which culture-specific or fallback-culture script file to send to the browser. It does this by using the culture-specific NeutralResourcesLanguageAttribute assembly attribute, the resources packaged with the assembly, and the UI culture of the browser (if any).
Stand-alone script files. The ScriptManager control defines the list of UI cultures that are supported by using the ResourceUICultures property of the ScriptReference object.
In debug mode. The ScriptManager control tries to render a culture-specific script file that contains debug information. For example, if the page is in debug mode and the current culture is set to en-MX, the control renders a script file that has a name such as scriptname.en-MX.debug.js, if the file exists. If the file does not exist, the debug file for the appropriate fallback culture is rendered
For more information about how to localize resources, see Localizing Resources for Component Libraries Overview.
Error Handling
The following examples show different scenarios for using the ScriptManager control.
Enabling Partial-Page Updates
The following example shows how to use the ScriptManager control to enable partial-page updates. In this example, a Calendar and a DropDownList control are inside an UpdatePanel control. By default, the value of the UpdateMode property is Always, and the value of the ChildrenAsTriggers property is true. Therefore, child controls of the panel cause an asynchronous postback.
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Sub DropDownSelection_Change(ByVal Sender As Object, ByVal E As EventArgs)
Calendar1.DayStyle.BackColor = _
System.Drawing.Color.FromName(ColorList.SelectedItem.Value)
End Sub
Protected Sub Calendar1_SelectionChanged(ByVal Sender As Object, ByVal E As EventArgs)
SelectedDate.Text = Calendar1.SelectedDate.ToString()
End Sub
</script>
<html >
<head id="Head1" runat="server">
<title>UpdatePanel Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1"
runat="server" />
<asp:UpdatePanel ID="UpdatePanel1"
runat="server">
<ContentTemplate>
<asp:Calendar ID="Calendar1"
ShowTitle="True"
OnSelectionChanged="Calendar1_SelectionChanged"
runat="server" />
<div>
Background:
<br />
<asp:DropDownList ID="ColorList"
AutoPostBack="True"
OnSelectedIndexChanged="DropDownSelection_Change"
runat="server">
<asp:ListItem Selected="True" Value="White">
White </asp:ListItem>
<asp:ListItem Value="Silver">
Silver </asp:ListItem>
<asp:ListItem Value="DarkGray">
Dark Gray </asp:ListItem>
<asp:ListItem Value="Khaki">
Khaki </asp:ListItem>
<asp:ListItem Value="DarkKhaki"> D
ark Khaki </asp:ListItem>
</asp:DropDownList>
</div>
<br />
Selected date:
<asp:Label ID="SelectedDate"
runat="server">None.</asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<br />
</div>
</form>
</body>
</html>
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void DropDownSelection_Change(Object sender, EventArgs e)
{
Calendar1.DayStyle.BackColor =
System.Drawing.Color.FromName(ColorList.SelectedItem.Value);
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
SelectedDate.Text =
Calendar1.SelectedDate.ToString();
}
</script>
<html >
<head id="Head1" runat="server">
<title>UpdatePanel Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1"
runat="server" />
<asp:UpdatePanel ID="UpdatePanel1"
runat="server">
<ContentTemplate>
<asp:Calendar ID="Calendar1"
ShowTitle="True"
OnSelectionChanged="Calendar1_SelectionChanged"
runat="server" />
<div>
Background:
<br />
<asp:DropDownList ID="ColorList"
AutoPostBack="True"
OnSelectedIndexChanged="DropDownSelection_Change"
runat="server">
<asp:ListItem Selected="True" Value="White">
White </asp:ListItem>
<asp:ListItem Value="Silver">
Silver </asp:ListItem>
<asp:ListItem Value="DarkGray">
Dark Gray </asp:ListItem>
<asp:ListItem Value="Khaki">
Khaki </asp:ListItem>
<asp:ListItem Value="DarkKhaki"> D
ark Khaki </asp:ListItem>
</asp:DropDownList>
</div>
<br />
Selected date:
<asp:Label ID="SelectedDate"
runat="server">None.</asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<br />
</div>
</form>
</body>
</html>
Handling Partial-Page Update Errors and Registering Script
The following example shows how to provide custom error handling during partial-page updates. By default, when an error occurs during partial-page updates, a JavaScript message box is displayed. This example demonstrates how to use custom error handling by providing a handler for the AsyncPostBackError event, and by setting the AsyncPostBackErrorMessage property in the event handler. You can also set the AllowCustomErrorsRedirect property to specify how the custom errors section of the Web.config file is used when an error occurs during partial-page updates. In this example, the default value of the AllowCustomErrorsRedirect property is used. This means that if the Web.config file contains a customErrors element, that element determines how errors are displayed. For more information, see customErrors Element (ASP.NET Settings Schema).
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Try
Dim a As Int32
a = Int32.Parse(TextBox1.Text)
Dim b As Int32
b = Int32.Parse(TextBox2.Text)
Dim res As Int32 = a / b
Label1.Text = res.ToString()
Catch ex As Exception
If (TextBox1.Text.Length > 0 AndAlso TextBox2.Text.Length > 0) Then
ex.Data("ExtraInfo") = " You can't divide " & _
TextBox1.Text & " by " & TextBox2.Text & "."
End If
Throw ex
End Try
End Sub
Protected Sub ScriptManager1_AsyncPostBackError(ByVal sender As Object, ByVal e As System.Web.UI.AsyncPostBackErrorEventArgs)
If (e.Exception.Data("ExtraInfo") <> Nothing) Then
ScriptManager1.AsyncPostBackErrorMessage = _
e.Exception.Message & _
e.Exception.Data("ExtraInfo").ToString()
Else
ScriptManager1.AsyncPostBackErrorMessage = _
"An unspecified error occurred."
End If
End Sub
</script>
<html >
<head id="Head1" runat="server">
<title>UpdatePanel Error Handling Example</title>
<style type="text/css">
#UpdatePanel1 {
width: 200px; height: 50px;
border: solid 1px gray;
}
#AlertDiv{
left: 40%; top: 40%;
position: absolute; width: 200px;
padding: 12px;
border: #000000 1px solid;
background-color: white;
text-align: left;
visibility: hidden;
z-index: 99;
}
#AlertButtons{
position: absolute; right: 5%; bottom: 5%;
}
</style>
</head>
<body id="bodytag">
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1"
OnAsyncPostBackError="ScriptManager1_AsyncPostBackError" runat="server" >
<Scripts>
<asp:ScriptReference Path="ErrorHandling.js" />
</Scripts>
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server" Width="39px"></asp:TextBox>
/
<asp:TextBox ID="TextBox2" runat="server" Width="39px"></asp:TextBox>
=
<asp:Label ID="Label1" runat="server"></asp:Label><br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="calculate" />
</ContentTemplate>
</asp:UpdatePanel>
<div id="AlertDiv">
<div id="AlertMessage">
</div>
<br />
<div id="AlertButtons">
<input id="OKButton" type="button" value="OK" runat="server" onclick="ClearErrorState()" />
</div>
</div>
</div>
</form>
</body>
</html>
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
try
{
int a = Int32.Parse(TextBox1.Text);
int b = Int32.Parse(TextBox2.Text);
int res = a / b;
Label1.Text = res.ToString();
}
catch (Exception ex)
{
if (TextBox1.Text.Length > 0 && TextBox2.Text.Length > 0)
{
ex.Data["ExtraInfo"] = " You can't divide " +
TextBox1.Text + " by " + TextBox2.Text + ".";
}
throw ex;
}
}
protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
{
if (e.Exception.Data["ExtraInfo"] != null)
{
ScriptManager1.AsyncPostBackErrorMessage =
e.Exception.Message +
e.Exception.Data["ExtraInfo"].ToString();
}
else
{
ScriptManager1.AsyncPostBackErrorMessage =
"An unspecified error occurred.";
}
}
</script>
<html >
<head id="Head1" runat="server">
<title>UpdatePanel Error Handling Example</title>
<style type="text/css">
#UpdatePanel1 {
width: 200px; height: 50px;
border: solid 1px gray;
}
#AlertDiv{
left: 40%; top: 40%;
position: absolute; width: 200px;
padding: 12px;
border: #000000 1px solid;
background-color: white;
text-align: left;
visibility: hidden;
z-index: 99;
}
#AlertButtons{
position: absolute; right: 5%; bottom: 5%;
}
</style>
</head>
<body id="bodytag">
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1"
OnAsyncPostBackError="ScriptManager1_AsyncPostBackError" runat="server" >
<Scripts>
<asp:ScriptReference Path="ErrorHandling.js" />
</Scripts>
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server" Width="39px"></asp:TextBox>
/
<asp:TextBox ID="TextBox2" runat="server" Width="39px"></asp:TextBox>
=
<asp:Label ID="Label1" runat="server"></asp:Label><br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="calculate" />
</ContentTemplate>
</asp:UpdatePanel>
<div id="AlertDiv">
<div id="AlertMessage">
</div>
<br />
<div id="AlertButtons">
<input id="OKButton" type="button" value="OK" runat="server" onclick="ClearErrorState()" />
</div>
</div>
</div>
</form>
</body>
</html>
Globalizing the Date and Time That Are Displayed in the Browser
The following example shows how to set the EnableScriptGlobalization property so that client script can display a culture-specific date and time in the browser. In the example, the Culture attribute of the @ Page directive is set to auto. As a result, the first language that is specified in the current browser settings determines the culture and UI culture for the page. For more information, see How to: Set the Culture and UI Culture for ASP.NET Web Page Globalization.
<%@ Page Language="VB" Culture="auto" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html >
<head id="Head1" runat="server">
<title>Globalization Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnableScriptGlobalization="true" runat="server">
</asp:ScriptManager>
<script type="text/javascript">
function pageLoad() {
Sys.UI.DomEvent.addHandler($get("Button1"), "click", formatDate);
}
function formatDate() {
var d = new Date();
try {
$get('Label1').innerHTML = d.localeFormat("dddd, dd MMMM yyyy HH:mm:ss");
}
catch(e) {
alert("Error:" + e.message);
}
}
</script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="False" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="Panel1" runat="server" GroupingText="Update Panel">
<asp:Button ID="Button1" runat="server" Text="Display Date" />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
<%@ Page Language="C#" Culture="auto" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html >
<head id="Head1" runat="server">
<title>Globalization Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnableScriptGlobalization="true" runat="server">
</asp:ScriptManager>
<script type="text/javascript">
function pageLoad() {
Sys.UI.DomEvent.addHandler($get("Button1"), "click", formatDate);
}
function formatDate() {
var d = new Date();
try {
$get('Label1').innerHTML = d.localeFormat("dddd, dd MMMM yyyy HH:mm:ss");
}
catch(e) {
alert("Error:" + e.message);
}
}
</script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="False" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="Panel1" runat="server" GroupingText="Update Panel">
<asp:Button ID="Button1" runat="server" Text="Display Date" />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
System..::.Object
System.Web.UI..::.Control
System.Web.UI..::.ScriptManager
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Windows 7, Windows Vista, Windows XP SP2, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003
The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
.NET Framework
Supported in: 3.5
Reference
Other Resources