Beruflich Dokumente
Kultur Dokumente
Introduction
The topics in this section provide information about how to create custom ECMAScript (JavaScript)
to use with the Microsoft ASP.NET AJAX client framework.
Introduction
Microsoft ASP.NET AJAX enables you to write rich, interactive applications in JavaScript that target
the browser. The Microsoft AJAX Library adds a type system and extensions to JavaScript objects in
order to provide namespaces, inheritance, interfaces, enumerations, reflection, and helpers for
strings and arrays. These additions provide functionality similar to the .NET Framework. They
enable you to write ASP.NET AJAX applications in a structured way that improves maintainability,
makes it easier to add features, and makes it easier to layer functionality.
In this section you will learn how to use the following JavaScript Microsoft AJAX Library features:
• Classes
• Namespaces
• Inheritance
• Interfaces
• Enumerations
• Reflection
Classes can have four kinds of members: fields, properties, methods, and events. Fields and
properties are name/value pairs that describe characteristics of an instance of a class. Fields are
composed of primitive types and are accessed directly, as in the following example:
myClassInstance.name="Fred"
With properties, the value can be any primitive or reference type and is accessed by get and set
accessor methods. In ASP.NET AJAX, the get and set accessors are separate functions, which by
convention use the prefix "get_" or "set_" in the function name. For example, to get or set a value
for a property such as cancel, you call the get_cancel or set_cancel methods.
A method is a function that performs an action instead of just returning a property value. Both
methods and properties are illustrated in the examples in this topic.
Events are programmatic notifications that particular actions have occurred. When an event is
raised, it can call one or more functions, referred to as handlers, to perform tasks that were waiting
for that event. For more information about events in ASP.NET AJAX, see the Sys.EventHandlerList
overview.
A namespace is a logical grouping of related classes (types). Namespaces enable you to group
common functionality. The following example demonstrates how to add a Person class to the Demo
namespace using the Type.registerNamespace and .registerClass methods.
To enable ASP.NET AJAX functionality for an ASP.NET Web page, you must add an
<asp:ScriptManager> control to the page. When the page is rendered, the appropriate script
references to ASP.NET AJAX libraries are generated automatically. The following example shows a
page with an <asp:ScriptManager> control.
cs
<asp:ScriptManager runat="server" ID="scriptManager" />
The following example shows how to register the namespace, create the class, and then register the
class.
cs
Type.registerNamespace("Demo");
Demo.Person.prototype = {
getFirstName: function() {
return this._firstName;
},
getLastName: function() {
return this._lastName;
},
getName: function() {
return this._firstName + ' ' + this._lastName;
},
dispose: function() {
alert('bye ' + this.getName());
}
}
Demo.Person.registerClass('Demo.Person', null, Sys.IDisposable);
To see a Web page that uses the previous script file, click the Run It button.
Run View
Access Modifiers
Most object-oriented programming languages include the concept of access modifiers, which allow
you to specify under what contexts a class or member is available, such as to outside programs,
internal classes within the same namespace, or only within a specific code block. There are no
access modifiers in JavaScript, however ASP.NET AJAX follows the convention that members with
names that start with the underscore character ("_") are considered private and not accessed
outside the class they are a part of.
Inheritance
Inheritance is the ability of one class to derive from another class. A derived class automatically
inherits all the fields, properties, methods and events of the base class. A derived class also adds
new members or overrides existing members of the base class to change their behavior.
The following example contains two classes defined in script: Person and Employee, where
Employee derives from Person. Both classes illustrate the use of private fields, and both have public
properties and methods. In addition, Employee overrides the toString implementation of the
Person class, and uses the base class functionality.
cs
Type.registerNamespace("Demo");
Demo.Person.prototype = {
getFirstName: function() {
return this._firstName;
},
getLastName: function() {
return this._lastName;
},
getEmailAddress: function() {
return this._emailAddress;
},
setEmailAddress: function(emailAddress) {
this._emailAddress = emailAddress;
},
getName: function() {
return this._firstName + ' ' + this._lastName;
},
dispose: function() {
alert('bye ' + this.getName());
},
sendMail: function() {
var emailAddress = this.getEmailAddress();
if (emailAddress.indexOf('@') < 0) {
emailAddress = emailAddress + '@example.com';
}
alert('Sending mail to ' + emailAddress + ' ...');
},
toString: function() {
return this.getName() + ' (' + this.getEmailAddress() + ')';
}
}
Demo.Person.registerClass('Demo.Person', null, Sys.IDisposable);
Demo.Employee = function(firstName, lastName, emailAddress, team, title) {
Demo.Employee.initializeBase(this, [firstName, lastName, emailAddress]);
this._team = team;
this._title = title;
}
Demo.Employee.prototype = {
getTeam: function() {
return this._team;
},
setTeam: function(team) {
this._team = team;
},
getTitle: function() {
return this._title;
},
setTitle: function(title) {
this._title = title;
},
toString: function() {
return Demo.Employee.callBaseMethod(this, 'toString') + '\r\n' +
this.getTitle() + '\r\n' + this.getTeam();
}
}
Demo.Employee.registerClass('Demo.Employee', Demo.Person);
To see a Web page that uses the previous script file, click the Run It button.
Run View
Interfaces
An interface is a logical structure that defines the input and output requirements of classes that
implement it. This enables a function to interact with classes that implement the same interface
regardless of what other functionality the class implements.
The following example defines a Tree base class and an IFruitTree interface. Apple and Banana,
two derived classes, implement the IFruitTree interface, but the Pine class does not.
cs
Type.registerNamespace("Demo.Trees");
Demo.Trees.IFruitTree = function() {}
Demo.Trees.IFruitTree.Prototype = {
bearFruit: function(){}
}
Demo.Trees.IFruitTree.registerInterface('Demo.Trees.IFruitTree');
Demo.Trees.Tree = function(name) {
this._name = name;
}
Demo.Trees.Tree.prototype = {
returnName: function() {
return this._name;
},
toStringCustom: function() {
return this.returnName();
},
makeLeaves: function() {}
}
Demo.Trees.Tree.registerClass('Demo.Trees.Tree');
Demo.Trees.Apple = function() {
Demo.Trees.Apple.initializeBase(this, ['Apple', 'red and crunchy']);
}
Demo.Trees.Apple.prototype = {
makeLeaves: function() {
alert('Medium-sized and desiduous');
},
toStringCustom: function() {
return 'FruitTree ' + Demo.Trees.Apple.callBaseMethod(this,
'toStringCustom');
}
}
Demo.Trees.Apple.registerClass('Demo.Trees.Apple', Demo.Trees.FruitTree);
Demo.Trees.GrannySmith = function() {
Demo.Trees.GrannySmith.initializeBase(this);
// You must set the _description feild after initializeBase
// or you will get the base value.
this._description = 'green and sour';
}
Demo.Trees.GrannySmith.prototype.toStringCustom = function() {
return Demo.Trees.GrannySmith.callBaseMethod(this, 'toStringCustom') + ' ... its
GrannySmith!';
}
Demo.Trees.GrannySmith.registerClass('Demo.Trees.GrannySmith', Demo.Trees.Apple);
Demo.Trees.Banana = function(description) {
Demo.Trees.Banana.initializeBase(this, ['Banana', 'yellow and squishy']);
}
Demo.Trees.Banana.prototype.makeLeaves = function() {
alert('Big and green');
}
Demo.Trees.Banana.registerClass('Demo.Trees.Banana', Demo.Trees.FruitTree);
Demo.Trees.Pine = function() {
Demo.Trees.Pine.initializeBase(this, ['Pine']);
}
Demo.Trees.Pine.prototype.makeLeaves = function() {
alert('Needles in clusters');
}
Demo.Trees.Pine.registerClass('Demo.Trees.Pine', Demo.Trees.Tree);
To see a Web page that uses the previous script file, click the Run It button.
Run View
Enumerations
An enumeration is a class that contains a set of named integer constants. You access the values like
properties, as in the following example:
myObject.color = myColorEnum.red
Enumerations provide an easily readable alternative to integer representations. For more
information about enumerations in ASP.NET AJAX, see Type.registerEnum Method.
The following example defines an enumeration of named colors that represent hexadecimal values.
cs
Type.registerNamespace("Demo");
To see a Web page that uses the previous script file, click the Run It button.
Run View
Reflection
Reflection is the ability to examine the structure and components of a program at run time. The
APIs that implement reflection are extensions of the Type class. These methods enable you to
collect information about an object, such as what it inherits from, whether it implements a particular
interface, and whether it is an instance of a particular class.
Creating Custom Client Script in ASP.NET AJAX
Introduction
Microsoft ASP.NET AJAX provides features that help you create client script and integrate it into
ASP.NET applications. This includes a type system and extensions to existing
ECMAScript (JavaScript) objects to give them the richness of .NET Framework classes. It also
provides the ScriptManager control to manage these script libraries and any custom script in your
application.
Creating Scripts
The Microsoft AJAX Library includes features that contribute to a richer, more powerful JavaScript
development experience.
The Type class adds object-oriented concepts such as classes and inheritance to JavaScript
programming. Any JavaScript object that is registered with the Type class automatically has access
to this functionality. For more information, see Extending JavaScript with ASP.NET AJAX.
The following example shows how to create and register a namespace and a class in a JavaScript
file:
cs
Type.registerNamespace("Demo");
Demo.Person.prototype = {
getFirstName: function() {
return this._firstName;
},
getLastName: function() {
return this._lastName;
},
getName: function() {
return this._firstName + ' ' + this._lastName;
},
dispose: function() {
alert('bye ' + this.getName());
}
}
Demo.Person.registerClass('Demo.Person', null, Sys.IDisposable);
Extensions to JavaScript base types provide additional functionality for those types. For more
information about these extensions, see the following topics:
The Sys.Debug class provides extensive debugging capabilities. For more information, see ASP.NET
AJAX Debugging and Tracing Overview and the Sys.Debug class overview.
Component developers can create debug and retail versions of script files that are automatically
managed by the ScriptManager control. You can identify debug versions of script files by including
".debug" as part of the script file name. For example, the following script file names identify retail
and debug versions of a file:
• Retail: Script.js
• Debug: Script.debug.js
You can also register scripts programmatically by creating script references in code and then adding
them to the Scripts collection. For more information, see Dynamically Assigning ASP.NET AJAX
Script References.
You can register scripts that are required for partial-page updates by using the registration methods
of the ScriptManager control. You can use these methods in the following ways:
• To generate client script in code, build a block of script as a string and pass it to the
RegisterClientScriptBlock) method.
• To add standalone script files that have no Microsoft AJAX Library dependencies, use the
RegisterClientScriptInclude) method.
• To add script files that are embedded in an assembly, use the RegisterClientScriptResource
method.
note
Scripts that are registered by using these methods do not have localization support.
For a complete list of script-registration methods and their uses, see the ScriptManager control
overview.
Any script blocks or inline script that you are registering must be inside the page's <form> element.
Otherwise, the script is not registered with the ScriptManager control and cannot access ASP.NET
AJAX functionality. For more information, see Sys.Application.initialize Method.
Introduction
In most scenarios, the easiest way to add a script file to an ASP.NET page is in markup, as in the
following example:
This topic addresses a simple page developer scenario. For adding script references in custom
controls, see Adding Client Behaviors to Web Server Controls Using ASP.NET AJAX Extensions.
Script references can specify script files or scripts embedded as resources in assemblies. Scripts can
exist in debug and retail versions. The following procedure shows how to assign a script reference to
a page in each of these situations.
note
All script files to be registered with the ScriptManager control must call the notifyScriptLoaded
method to notify the application that the script has finished loading. Assembly-based scripts should
not call this method in most cases. For more information, see Sys.Application.notifyScriptLoaded.
1. If you do not know the ID of the <asp:ScriptManager> element on the page, call the
GetCurrent() method of the ScriptManager control to get the current instance of the control.
Test for null in case there is no ScriptManager control on the page. If you know that there is an
<asp:ScriptManager> element on the page and you know its ID value, you can skip this step.
The following example shows how to test for the existence of a ScriptManager control on a page,
and then either get the current instance or create a new instance.
CS
// If there is a ScriptManager on the page, use it.
// If not, throw an exception.
ScriptManager Smgr = ScriptManager.GetCurrent(Page);
if (Smgr == null) throw new Exception("ScriptManager not found.");
VB
' If there is a ScriptManager on the page, use it.
' If not, throw an exception.
Dim SMgr As ScriptManager
If ScriptManager.GetCurrent(Page) Is Nothing Then
Throw New Exception("ScriptManager not found.")
Else : SMgr = ScriptManager.GetCurrent(Page)
End If
CS
ScriptReference SRef = new ScriptReference();
VB
Dim SRef As ScriptReference
SRef = New ScriptReference()
3. For file-based scripts, if you know that the ScriptPath property of the ScriptManager
control is set to the correct location for the script file, set the Name property of the
ScriptReference instance to the name of the script file. Otherwise, set the Path property of the
ScriptReference object to the absolute, relative, or application-relative URL of the script file to
add.
CS
// If you know that Smgr.ScriptPath is correct...
SRef.Name = "Script.js";
4. If the script is part of an assembly, set the Name and Assembly properties of the
ScriptReference instance.
CS
SRef.Name = "Script.js";
SRef.Assembly = "ScriptAssembly";
VB
SRef.Name = "Script.js"
SRef.Assembly = "ScriptAssembly"
5. Specify whether to run debug or release versions of the script. To set this mode for all
scripts on the page, set the ScriptMode property of the ScriptManager control. To set debug
mode for an individual script, set the ScriptMode property of the ScriptReference object.
CS
// To set ScriptMode for all scripts on the page...
Smgr.ScriptMode = ScriptMode.Release;
VB
' To set ScriptMode for all scripts on the page...
SMgr.ScriptMode = ScriptMode.Release
note
If the Path property of the ScriptReference object is not set, the ScriptMode property of the
ScriptManager control is set to Release by default. If the Path property of the ScriptReference
object is set, the ScriptManager control looks for both debug and release scripts unless its
ScriptMode property is set to a specific mode.
6. Add the ScriptReference object to the Scripts collection of the ScriptManager control.
CS
Smgr.Scripts.Add(SRef);
VB
SMgr.Scripts.Add(SRef)
Introduction
In this tutorial you will use JavaScript to display days, months, and other date-related values in
globalized formats. Microsoft ASP.NET 2.0 AJAX Extensions provides client globalization support
based on a setting in the ScriptManager control. After these globalization settings have been applied
to the Web application, you can use client script to format a JavaScript Date or Number object
based on a culture value. This does not require a postback to the server. The culture value that is
used by the client script is based on the default culture setting provided by the user's browser
settings. Alternatively, it can be set to a specific culture value by using server settings or server
code in your application.
A culture value provides information about a specific culture (locale). The culture value is a
combination of two letters for a language and two uppercase letters for a country or region.
Examples include es-MX (Spanish Mexico), es-CO (Spanish Columbia), and fr-CA (French Canada).
The Microsoft ASP.NET AJAX Date extensions add functionality to the JavaScript Date object by
providing the localeFormat method. This method enables a Date object to be formatted based on
the browser language setting, on server settings, or on server code. These settings affect the server
culture value, which is then interpreted by the server to generate a client object exposed by the
Sys.CultureInfo.CurrentCulture property. It is this object that is used when formatting dates.
For more information about cultures and locales, see ASP.NET Globalization and Localization and the
CultureInfo class overview.
Prerequisites
You can see the code in action in this tutorial by clicking the Run It buttons. To implement the
procedures in your own development environment you need:
• Microsoft Visual Studio 2005 or Microsoft Visual Web Developer Express Edition.
• The latest release of Microsoft ASP.NET AJAX installed and configured. For more
information, see Installing ASP.NET AJAX.
3. On the Tools menu, click Internet Options, click the General tab, click Language, and
then set the language preference to es-MX. (Spanish Mexico). Remove other locales from the
list.
note
If you use a different browser, you can change language settings in that browser.
5. Create or open an ASP.NET AJAX Web page and switch to Design view.
6. Select the ScriptManager control and set its EnableScriptGlobalization property to true.
note
If the page does not contain a ScriptManager control, add one from the AJAX Extensions tab of
the toolbox.
7. In the AJAX Extensions tab of the toolbox, double-click the UpdatePanel control to add
an update panel to the page.
8. Set the ChildrenAsTriggers property of the UpdatePanel control tofalse.
10. Click inside the UpdatePanel control. Then in the Standard tab of the toolbox, double-click
the Button and Label controls to add a button and a label to the UpdatePanel control.
note
Make sure that you add the Label and Button controls inside the UpdatePanel control.
CS
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);
}
}
VB
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);
}
}
This code adds a Click handler to the button named Button1. The code calls the formatDate
function, which creates a new Date object and displays the formatted date in the element named
Label1. The date is formatted by using the localeFormat function that is part of the Microsoft
AJAX Library extensions for the Date object.
13. Modify the application's Web.config file by including the following globalization section in
the <system.web> element.
The "auto" setting specifies that the ACCEPT-LANGUAGE header in the browser request (which
provides the user's language preference list) is used to set the culture value.
14. Save your changes, and then run the Web page in the browser where you changed
language settings.
15. Click the Display Date button to see the globalized date value that is based on the
browser language settings.
To see the full example in action, click the Run It button. The example is styled to better show
the region of the page that the UpdatePanel represents.
Run View
16. When you are finished, reset the language settings in the browser.
1. Modify the application's Web.config file by including the following globalization section in
the <system.web> element:
3. Click the Display Date button to see the globalized date value.
The date formatting is now based on the culture attribute in the configuration file instead of on
the browser language preference. Setting the culture in the configuration file overrides browser
language settings.
To see the full example in action, click the Run It button. The example is styled to better show
the region of the page that the UpdatePanel represents.
Run View
1. Modify the @ Page directive of the page you are working with to include the de-DE culture
value:
3. Click the Display Date button to see the globalized date value.
The date formatting is now based on the Culture attribute of the @ Page directive.
To see the full example in action, click the Run It button. The example is styled to better show
the region of the page that the UpdatePanel represents.
Run View
CS
protected override void InitializeCulture()
{
this.Culture = "it-IT";
}
VB
Protected Overrides Sub InitializeCulture()
Me.Culture = "it-IT"
End Sub
This code overrides the InitializeCulture() method of the base Page class. This is the appropriate
time in the page life cycle to change the culture programmatically.
2. Save your changes, and then run the Web page in the browser.
Introduction
In this tutorial you will include a JavaScript file as an embedded resource in an assembly. You
embed a JavaScript file when you have a client script component that must be distributed with an
assembly that you have created. For example, you might have created a custom ASP.NET server
control that uses JavaScript files to implement ASP.NET AJAX functionality. You can embed the
JavaScript files in the assembly, and they can then be referenced from a Web application that
registers the assembly.
note
You cannot use Visual Web Developer 2005 Express Edition, because Visual Web Developer
Express Edition does not enable you to create the Class Library project required in the
tutorial.
• The latest release of Microsoft ASP.NET AJAX installed and configured. For more
information, see Installing ASP.NET AJAX.
CS
BorderAnimation = function(color) {
this._color = color;
}
BorderAnimation.prototype = {
animate: function(panelElement) {
var s = panelElement.style;
s.borderWidth = '2px';
s.borderColor = this._color;
s.borderStyle = 'solid';
window.setTimeout(
function() {{
s.borderWidth = 0;
}},
500);
}
}
vb
BorderAnimation = function(color) {
this._color = color;
}
BorderAnimation.prototype = {
animate: function(panelElement) {
var s = panelElement.style;
s.borderWidth = '2px';
s.borderColor = this._color;
s.borderStyle = 'solid';
window.setTimeout(
function() {{
s.borderWidth = 0;
}},
500);
}
}
The code contains a JavaScript function that temporarily displays a colored border around an
UpdatePanel control.
5. In the Properties window for the UpdatePanelAnimation.js file, set Build Action to
Embedded Resource.
7. Replace any code in the CustomControl file with the following code:
CS
using System;
using System.Drawing;
using System.Web.UI;
using System.Web;
using System.Globalization;
namespace SampleControl
{
public class UpdatePanelAnimationWithClientResource : Control
{
private string _updatePanelID;
private Color _borderColor;
private Boolean _animate;
public Color BorderColor
{
get
{
return _borderColor;
}
set
{
_borderColor = value;
}
}
UpdatePanel updatePanel =
(UpdatePanel)FindControl(UpdatePanelID);
ScriptManager.RegisterStartupScript(
this,
typeof(UpdatePanelAnimationWithClientResource),
ClientID,
script,
true);
}
}
}
}
vb
Imports System.Web.UI
Imports System.Drawing
Imports System.Globalization
ScriptManager.RegisterStartupScript( _
Me, _
GetType(UpdatePanelAnimationWithClientResource), _
ClientID, _
script, _
True)
End If
End Sub
End Class
This class contains properties for customizing the border that is displayed around the
UpdatePanel control. The code also registers JavaScript code to use in a Web page. The code
creates a handler for the load event of the Sys.Application object. The animate function in the
UpdatePanelAnimation.js file is called when a partial-page update is processed.
CS
[assembly: System.Web.UI.WebResource("SampleControl.UpdatePanelAnimation.js",
"application/x-javascript")]
vb
<Assembly: System.Web.UI.WebResource("SampleControl.UpdatePanelAnimation.js",
"application/x-javascript")>
note
The AssemblyInfo.vb file is in the My Project node of Solution Explorer. If you do not see any
files in the My Project node, in the Project menu, click Show All Files. The AssemblyInfo.cs
file is in the Properties node of Solution Explorer.
The WebResource definition must include the namespace and the name of the .js file.
When compilation finishes, you will have an assembly named SampleControl.dll. The JavaScript
code in the UpdatePanelAnimation.js file is embedded in this assembly as a resource.
Referencing the Embedded Script File
You will now reference the embedded script file in a Web application.
note
Although you can create the Class Library project and the Web site in the same Visual Studio
solution, in this tutorial it is not assumed that you are doing so. Having the projects in separate
solutions emulates how a control developer and a page developer would work separately. However,
for convenience you can create both projects in the same solution and make small adjustments to
procedures in the tutorial.
3. Add the SampleControl.dll from the bin\Debug or bin\Release directory of the Class
Library project to the Bin folder of the Web site.
note
If you created the Class Library project and the Web site in the same Visual Studio solution, you
can add a reference from the Class Library project directly to the Web site. For details, see How
to: Add a Reference to a Visual Studio Project in a Web Site.
4. Replace the code in the Default.aspx file with the following code:
CS
<%@ Page Language="C#" %>
<%@ Register TagPrefix="Samples" Namespace="SampleControl"
Assembly="SampleControl" %>
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ScriptReference</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1"
EnablePartialRendering="True"
runat="server">
<Scripts>
<asp:ScriptReference Assembly="SampleControl"
Name="SampleControl.UpdatePanelAnimation.js" />
</Scripts>
</asp:ScriptManager>
<Samples:UpdatePanelAnimationWithClientResource
ID="UpdatePanelAnimator1"
BorderColor="Green"
Animate="true"
UpdatePanelID="UpdatePanel1"
runat="server" >
</Samples:UpdatePanelAnimationWithClientResource>
<asp:UpdatePanel ID="UpdatePanel1"
UpdateMode="Conditional"
runat="server">
<ContentTemplate>
<asp:Calendar ID="Calendar2"
runat="server">
</asp:Calendar>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
vb
<%@ Page Language="VB" AutoEventWireup="true" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>ScriptReference</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1"
EnablePartialRendering="True"
runat="server">
<Scripts>
<asp:ScriptReference Assembly="SampleControl"
Name="SampleControl.UpdatePanelAnimation.js" />
</Scripts>
</asp:ScriptManager>
<Samples:UpdatePanelAnimationWithClientResource
ID="UpdatePanelAnimator1"
BorderColor="Green"
Animate="true"
UpdatePanelID="UpdatePanel1"
runat="server" >
</Samples:UpdatePanelAnimationWithClientResource>
<asp:UpdatePanel ID="UpdatePanel1"
UpdateMode="Conditional"
runat="server">
<ContentTemplate>
<asp:Calendar ID="Calendar2"
runat="server">
</asp:Calendar>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
This code includes an <asp:ScriptReference> element that references the assembly and the .js
file that you created in the previous procedure.
You will see a green border around the UpdatePanel control every time that you click a date in
the calendar.
Review
This tutorial showed you how to embed a JavaScript file as a resource in an assembly. The
embedded script file can be accessed in a Web application that contains the assembly.
The next step is to learn how to embed localized resources in an assembly for use in client script.
For more information, see Embed Localized Resources for a JavaScript File.
Embedding Localized Resources for a JavaScript File
Introduction
In this tutorial you will include a JavaScript file as an embedded resource in an assembly and
include localized strings for use in the JavaScript file. You embed a JavaScript file in an assembly
when you have a client script component that must be distributed with the assembly. The JavaScript
file can be referenced from a Web application that registers the assembly. You embed localized
resources when you have to modify values that are used by the JavaScript file for different
languages and cultures.
note
You cannot use Visual Web Developer 2005 Express Edition, because Visual Web Developer
Express Edition does not enable you to create the Class Library project required in the
tutorial.
• The latest release of Microsoft ASP.NET AJAX installed and configured. For more
information, see Installing ASP.NET AJAX.
cs
function CheckAnswer()
{
var firstInt = $get('firstNumber').innerText;
var secondInt = $get('secondNumber').innerText;
var userAnswer = $get('userAnswer');
if ((Number.parseLocale(firstInt) + Number.parseLocale(secondInt)) ==
userAnswer.value)
{
alert(Answer.Correct);
return true;
}
else
{
alert(Answer.Incorrect);
return false;
}
}
vb
function CheckAnswer()
{
var firstInt = $get('firstNumber').innerText;
var secondInt = $get('secondNumber').innerText;
var userAnswer = $get('userAnswer');
if ((Number.parseLocale(firstInt) + Number.parseLocale(secondInt)) ==
userAnswer.value)
{
alert(Answer.Correct);
return true;
}
else
{
alert(Answer.Incorrect);
return false;
}
}
The script checks the user's result for adding two numbers. It uses the alert function to let the
user know if the answer is correct. The message displayed in the alert dialog box is read from a
localized resource without a postback to the server. A placeholder named Answer is used in the
script to identify which resource files contain the localized strings. The Answer placeholder will be
defined later in this procedure.
5. In the Properties window for CheckAnswer.js, set Build Action to Embedded Resource.
cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Resources;
namespace LocalizingScriptResources
{
public class ClientVerification : Control
{
private Button _button;
private Label _firstLabel;
private Label _secondLabel;
private TextBox _answer;
private int _firstInt;
private int _secondInt;
ResourceManager rm = new
ResourceManager("LocalizingScriptResources.VerificationResources",
this.GetType().Assembly);
Controls.Clear();
Controls.Add(_firstLabel);
Controls.Add(new LiteralControl(" + "));
Controls.Add(_secondLabel);
Controls.Add(new LiteralControl(" = "));
Controls.Add(_answer);
Controls.Add(_button);
}
}
}
vb
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Resources
Dim rm = New
ResourceManager("LocalizingScriptResources.VerificationResources",
Me.GetType().Assembly)
Controls.Clear()
Controls.Add(_firstLabel)
Controls.Add(New LiteralControl(" + "))
Controls.Add(_secondLabel)
Controls.Add(New LiteralControl(" = "))
Controls.Add(_answer)
Controls.Add(_button)
End Sub
End Class
The code creates a custom ASP.NET control. It contains two Label controls, a TextBox control,
and a Button control. The code displays two randomly generated integers and provides a text
box for an answer. When the button is clicked, the CheckAnswer function is called.
9. Add a string resource named Correct with a value of "Yes, your answer is correct."
10. Add a string resource named Incorrect with a value of "No, your answer is incorrect."
11. Add a string resource named Verify with a value of "Verify Answer".
This resource is not retrieved by using client script. Instead, it is used to set to the Text property
of the Button control when the button is created.
14. Add a string resource named Correct with a value of "Si, la risposta e’ corretta."
15. Add a string resource named Incorrect with a value of "No, la risposta e’ sbagliata."
16. Add a string resource named Verify with a value of "Verificare la risposta".
As with the "Verify" resource that you created in English, this resource is not retrieved by using
client script. Instead, it is used to set the Text property of the Button control when the button is
created.
18. Add the following line to the AssemblyInfo file. You can specify any name for the type
name in the ScriptResourceAttribute, but it must match the type name that is used in the client
script. In this example, it is set to Answer.
cs
[assembly: System.Web.UI.WebResource("LocalizingScriptResources.CheckAnswer.js",
"application/x-javascript")]
[assembly:
System.Web.UI.ScriptResource("LocalizingScriptResources.CheckAnswer.js",
"LocalizingScriptResources.VerificationResources", "Answer")]
vb
<Assembly: System.Web.UI.WebResource("LocalizingScriptResources.CheckAnswer.js",
"application/x-javascript")>
<Assembly:
System.Web.UI.ScriptResource("LocalizingScriptResources.CheckAnswer.js",
"LocalizingScriptResources.VerificationResources", "Answer")>
note
The AssemblyInfo.vb file is in the My Project node of Solution Explorer. If you do not see any
files in the My Project node, in the Project menu, click Show All Files. The AssemblyInfo.cs
file is in the Properties node of Solution Explorer.
The WebResource definition must include the namespace and the name of the .js file. The
ScriptResource definition does not include the file name extension or the localized .resx files.
When compilation finishes, you will have an assembly named LocalizingScriptResources.dll. The
JavaScript code in the CheckAnswer.js file and the resources in the two .resx files are embedded
in this assembly as resources.
note
Although you can create the Class Library project and the Web site in the same Visual Studio
solution, in this tutorial it is not assumed that you are doing so. Having the projects in separate
solutions emulates how a control developer and a page developer would work separately. However,
for convenience you can create both projects in the same solution and make small adjustments to
procedures in the tutorial.
3. Add the LocalizingScriptResources.dll assembly from the Class Library project to the Bin
folder.
note
If you created the Class Library project and the Web site in the same Visual Studio solution, you
can add a reference from the Class Library project directly to the Web site. For details, see How
to: Add a Reference to a Visual Studio Project in a Web Site.
4. Create a folder in the Bin folder and give it the name it (for Italian).
5. Add the LocalizingScriptResources.resources.dll satellite assembly from the it folder in
the LocalizingScriptResources project to the it folder in the Web site.
cs
<%@ Page Language="C#" AutoEventWireup="true" UICulture="auto" Culture="auto" %>
<%@ Register TagPrefix="Samples" Namespace="LocalizingScriptResources"
Assembly="LocalizingScriptResources" %>
<script runat="server">
vb
<%@ Page Language="VB" AutoEventWireup="true" UICulture="auto" Culture="auto" %>
<%@ Register TagPrefix="Samples" Namespace="LocalizingScriptResources"
Assembly="LocalizingScriptResources" %>
<script runat="server">
The control that you created in the LocalizingScriptResources project is included on the page.
This control displays two numbers to add, a TextBox control for the user to enter an answer, and
a button that calls the script in the CheckAnswer function when it is clicked. The CheckAnswer
function runs in the browser and displays a localized message that indicates whether the answer
is correct.
You must set the EnableScriptLocalization property of the ScriptManager object to true to
enable the ScriptManager control to retrieve localized resources. You must also set the Culture
and UICulture to "auto" to display the strings that are based on the browser's settings. The page
contains a DropDownList control that you can use to change the language settings without
changing the settings in the browser. When the SelectedIndex property of the DropDownList
control changes, the CurrentUICulture property of the CurrentThread instance is set to the value
that you have selected.
You will see an addition problem with two randomly generated numbers and a TextBox control
for entering an answer. When you enter an answer and click the Verify Answer button, you see
the response in a message window that tells you whether the answer is correct. By default, the
response will be returned in English. However, if you have set Italian as your preferred language
in the browser, the answer will be in Italian. You can change the language for the response
either by selecting a language in the DropDownList control or by changing the preferred
language in the browser.
Review
This tutorial introduced the concept of embedding a JavaScript file as a resource in an assembly and
including localized strings. The embedded script file can be referenced and accessed in a Web
application that contains the assembly. The localized strings will be displayed based on the language
setting in the browser or the language provided by the user.