Sie sind auf Seite 1von 36

ASP.

NET AJAX and JavaScript

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.

Extending JavaScript with ASP.NET AJAX

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, Members, and Namespaces


Classes are reference types. All classes in JavaScript derive from object. (Similarly, in the .NET
Framework class library, all classes derive from ) Classes in ASP.NET AJAX enable you to create
objects and components that derive from base classes in the Microsoft AJAX Library by using an
object-oriented programming model.

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 = function(firstName, lastName, emailAddress) {


this._firstName = firstName;
this._lastName = lastName;
this._emailAddress = emailAddress;
}

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 = function(firstName, lastName, emailAddress) {


this._firstName = firstName;
this._lastName = lastName;
this._emailAddress = emailAddress;
}

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.FruitTree = function(name, description) {


Demo.Trees.FruitTree.initializeBase(this, [name]);
this._description = description;
}
Demo.Trees.FruitTree.prototype.bearFruit = function() {
return this._description;
}
Demo.Trees.FruitTree.registerClass('Demo.Trees.FruitTree', Demo.Trees.Tree,
Demo.Trees.IFruitTree);

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");

// Define an enumeration type and register it.


Demo.Color = function(){};
Demo.Color.prototype =
{
Red: 0xFF0000,
Blue: 0x0000FF,
Green: 0x00FF00,
White: 0xFFFFFF
}
Demo.Color.registerEnum("Demo.Color");

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 = function(firstName, lastName, emailAddress) {


this._firstName = firstName;
this._lastName = lastName;
this._emailAddress = emailAddress;
}

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:

• Array Type Extensions

• Boolean Type Extensions

• Date Type Extensions

• Error Type Extensions

• Number Type Extensions

• Object Type Extensions

• String Type Extensions

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

Integrating Client Script into ASP.NET Web Applications


Any ASP.NET Web page can access a script file by referring to it in a <script> block, as in the
following example:

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


However, a script invoked in this manner cannot participate in partial-page rendering or access
certain components of the Microsoft AJAX Library. To make a script file available for partial-page
rendering in an ASP.NET AJAX Web application, the script must be registered with the
ScriptManager control on the page. To register a script file, create a ScriptReference object that
points to the file question and that adds it to the Scripts collection. The following example shows
how to do this in markup:
<asp:ScriptManager ID="SMgr" runat="server">
<Scripts>
<asp:ScriptReference path="./Script.js" />
</Scripts>
</asp:ScriptManager>
For script files to be processed correctly by the ScriptManager control, each file must include a call
to the Sys.Application.notifyScriptLoaded method at the end of the file. This call notifies the
application that the file has finished loading. The following example shows the code to use for this
purpose:

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();


If your script is embedded in an assembly, you do not have to include a notification statement in
the script. You also do not have to specify a path attribute in the script reference. However, you
must provide the name of the assembly without the file name extension, as shown in the following
example:

<asp:ScriptManager ID="SMgr" runat="server">


<Scripts>
<asp:ScriptReference Name="Script.js" Assembly="ScriptAssembly"/>
</Scripts>
</asp:ScriptManager>
note
This scenario is not common for page developers, because most controls with embedded script
libraries reference their scripts internally. For more information, see Embedding a JavaScript File as
a Resource in an Assembly.

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.

Dynamically Assigning ASP.NET AJAX Script References

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:

<asp:ScriptManager ID="SMgr" runat="server">


<Scripts>
<asp:ScriptReference Path="./Script.js" />
</Scripts>
</asp:ScriptManager>
However, it is also possible to add script references dynamically. Page developers can do this to
have more control over how a script is added. For example, they might add scripts dynamically to
help conserve memory resources by not loading a large script library unless it is needed. Or they
might load different versions of scripts for different types of users. Control developers add scripts
dynamically when they create script controls or extender controls in order to make script resources
automatically available to the page that hosts the control.

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.

To dynamically add a script reference to a page

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

2. Create a ScriptReference object.

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";

// Or, to specify an app-relative path...


SRef.Path = "~/Scripts/Script.js";
VB
' If you know that Smgr.ScriptPath is correct...
SRef.Name = "Script.js"

' Or, to specify an app-relative path...


SRef.Path = "~/Scripts/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.

The following example demonstrates both options.

CS
// To set ScriptMode for all scripts on the page...
Smgr.ScriptMode = ScriptMode.Release;

//Or, to set the ScriptMode just for the one script...


SRef.ScriptMode = ScriptMode.Debug;

//If they conflict, the setting on the ScriptReference wins.

VB
' To set ScriptMode for all scripts on the page...
SMgr.ScriptMode = ScriptMode.Release

'Or, set ScriptMode for just for the one script...


SRef.ScriptMode = ScriptMode.Debug

'If they conflict, the setting on the ScriptReference wins.

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)

Globalizing a Date by Using Client Script

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.

• An ASP.NET AJAX Web site.

Globalizing a Date Based on Browser Settings


To begin, you will use the language preference settings in the browser to specify how to format a
date.

To globalize a date based on the browser language preference


1. Close any open instances of Microsoft Internet Explorer or of your browser so that all new
instances will use a new locale setting.

2. Open a new instance of Microsoft Internet Explorer.

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.

4. Close the browser window.

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.

9. Set the UpdateMode property of the UpdatePanel control toConditional.

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.

11. Switch to Source view.

12. Add the following client script to the page.

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.

<globalization culture="auto" />


note

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.

Globalizing a Date Based on Configuration Settings


If you have to display formatted dates in multiple pages, you can set the culture in the application's
configuration file. The format settings then apply to dates in all pages.

To globalize a date based on configuration file settings

1. Modify the application's Web.config file by including the following globalization section in
the <system.web> element:

<globalization culture="fr-CA" />


2. Save your changes, and then run the Web page in your browser.

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

Globalizing a Date Based on Page Settings


As an alternative to using the configuration file to set the culture value, you can use the Culture
attribute of the @ Page directive. The Culture attribute of the @ Page directive takes precedence
over the setting in the configuration file and over browser language settings.

To globalize a date based on a page setting

1. Modify the @ Page directive of the page you are working with to include the de-DE culture
value:

<%@ Page Language="C#" AutoEventWireup="true" Culture="de-DE" %>


2. Save your changes, and then run the Web page in the browser.

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

Globalizing a Date Programmatically


If you have to programmatically modify the Culture setting of a page, you can override the page's
InitializeCulture() method in server code. The InitializeCulture() method takes precedence over
culture settings in the @ Page directive, in the configuration file, and in the browser.

To globalize a date programmatically


1. Add the following method to the page:

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.

3. Click the Display Date button to see the globalized date.

The date value is now being formatted based on server code.


Embedding a JavaScript File as a Resource in an
Assembly

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.

To implement the procedures in this tutorial you need:

• Microsoft Visual Studio 2005.

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.

Creating an Assembly that Contains an Embedded JavaScript File


To begin, you will create a file with JavaScript code that you want to embed in the assembly.

To embed a client script file in an assembly


1. Create a new Class Library project named SampleControl.

2. Add references to the System.Web, System.Drawing, and System.Web.Extensions


namespaces to the project.

3. Add a new JScript file named UpdatePanelAnimation.js to the project.

4. Add the following code to the UpdatePanelAnimation.js file:

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.

6. Add a class file named CustomControl to the project.

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;
}
}

public string UpdatePanelID


{
get
{
return _updatePanelID;
}
set
{
_updatePanelID = value;
}
}

public Boolean Animate


{
get
{
return _animate;
}
set
{
_animate = value;
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (Animate)
{

UpdatePanel updatePanel =
(UpdatePanel)FindControl(UpdatePanelID);

string script = String.Format(


CultureInfo.InvariantCulture,
@"
Sys.Application.add_load(function(sender, args) {{
var {0}_borderAnimation = new BorderAnimation('{1}');
var panelElement = document.getElementById('{0}');
if (args.get_isPartialLoad()) {{
{0}_borderAnimation.animate(panelElement);
}}
}})
",
updatePanel.ClientID,
ColorTranslator.ToHtml(BorderColor));

ScriptManager.RegisterStartupScript(
this,
typeof(UpdatePanelAnimationWithClientResource),
ClientID,
script,
true);
}
}
}
}

vb
Imports System.Web.UI
Imports System.Drawing
Imports System.Globalization

Public Class UpdatePanelAnimationWithClientResource


Inherits Control

Private _updatePanelID As String


Private _borderColor As Color
Private _animate As Boolean

Public Property BorderColor() As Color


Get
Return _borderColor
End Get
Set(ByVal value As Color)
_borderColor = value
End Set
End Property

Public Property UpdatePanelID() As String


Get
Return _updatePanelID
End Get
Set(ByVal value As String)
_updatePanelID = value
End Set
End Property

Public Property Animate() As Boolean


Get
Return _animate
End Get
Set(ByVal value As Boolean)
_animate = value
End Set
End Property

Protected Overrides Sub OnPreRender(ByVal e As EventArgs)


MyBase.OnPreRender(e)
If (Animate) Then
Dim updatePanel As UpdatePanel = CType(Me.FindControl(UpdatePanelID),
UpdatePanel)

Dim script As String = String.Format( _


CultureInfo.InvariantCulture, _
"Sys.Application.add_load(function(sender, args) {{var
{0}_borderAnimation = new BorderAnimation('{1}');var panelElement =
document.getElementById('{0}');if (args.get_isPartialLoad())
{{{0}_borderAnimation.animate(panelElement);}}}});", _
updatePanel.ClientID, _
ColorTranslator.ToHtml(BorderColor))

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.

8. Add the following line to the AssemblyInfo file.

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.

9. Build the project.

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.

To reference the embedded script file


1. Create a new AJAX-enabled Web site.

2. Create a Bin folder in the root directory of the Web site.

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" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<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" %>

<%@ Register TagPrefix="Samples" Namespace="SampleControl"


Assembly="SampleControl" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

5. Run the project.

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.

To implement the procedures in this tutorial you need:

• Microsoft Visual Studio 2005.

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.

Creating an Assembly that Contains an Embedded JavaScript File


You will begin by creating an assembly (.dll file) that contains the JavaScript file that you want to
treat as a resource. You will do so by creating a Class Library project in Visual Studio, which creates
an assembly as its output.

To embed a client script file and resources in an assembly


1. Create a new Class Library project and name it LocalizingScriptResources.

2. Add references to the System.Web and System.Web.Extensions namespaces to the


project.

3. Add a new JScript file to the project and name it CheckAnswer.js.

4. Add the following code to the CheckAnswer.js file.

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.

6. Add a class file to the project and name it ClientVerification.


7. Replace any code in the ClientVerification file with the following code:

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;

protected override void CreateChildControls()


{
Random random = new Random();
_firstInt = random.Next(0, 20);
_secondInt = random.Next(0, 20);

ResourceManager rm = new
ResourceManager("LocalizingScriptResources.VerificationResources",
this.GetType().Assembly);
Controls.Clear();

_firstLabel = new Label();


_firstLabel.ID = "firstNumber";
_firstLabel.Text = _firstInt.ToString();

_secondLabel = new Label();


_secondLabel.ID = "secondNumber";
_secondLabel.Text = _secondInt.ToString();

_answer = new TextBox();


_answer.ID = "userAnswer";

_button = new Button();


_button.ID = "Button";
_button.Text = rm.GetString("Verify");
_button.OnClientClick = "return CheckAnswer();";

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

Public Class ClientVerification


Inherits Control

Private _button As Button


Private _firstLabel As Label
Private _secondLabel As Label
Private _answer As TextBox
Private _firstInt As Int32
Private _secondInt As Int32

Protected Overrides Sub CreateChildControls()


Dim random = New Random()
_firstInt = random.Next(0, 20)
_secondInt = random.Next(0, 20)

Dim rm = New
ResourceManager("LocalizingScriptResources.VerificationResources",
Me.GetType().Assembly)
Controls.Clear()

_firstLabel = New Label()


_firstLabel.ID = "firstNumber"
_firstLabel.Text = _firstInt.ToString()

_secondLabel = New Label()


_secondLabel.ID = "secondNumber"
_secondLabel.Text = _secondInt.ToString()

_answer = New TextBox()


_answer.ID = "userAnswer"

_button = New Button()


_button.ID = "Button"
_button.Text = rm.GetString("Verify")
_button.OnClientClick = "return CheckAnswer();"

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.

8. Add a resources file to the project and name it VerificationResources.resx.

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.

12. Save and close the VerificationResources.resx file.

13. Add a resources file named VerificationResources.it.resx to the project.

This file will contain resource strings in Italian.

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.

17. Save and close the VerificationResources.it.resx file.

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.

19. Build the project.

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.

You will also have an assembly named LocalizingScriptResources.resources.dll (a satellite


assembly) that contains the Italian resources for server code.

Referencing the Embedded Script and Resources


You can now use the assembly in an AJAX-enabled ASP.NET Web site. You will be able to read the
.js file and the resource values in client script.

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.

To reference the embedded script and resources


1. Open Visual Studio and create a new AJAX-enabled Web site.

2. Add a Bin folder under the Web site root.

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.

6. Add a new ASP.NET Web page to the project.

7. Replace the code in the page with the following code:

cs
<%@ Page Language="C#" AutoEventWireup="true" UICulture="auto" Culture="auto" %>
<%@ Register TagPrefix="Samples" Namespace="LocalizingScriptResources"
Assembly="LocalizingScriptResources" %>
<script runat="server">

protected void Page_Load(object sender, EventArgs e)


{
if (IsPostBack)
{
System.Threading.Thread.CurrentThread.CurrentUICulture =
System.Globalization.CultureInfo.CreateSpecificCulture(selectLanguage.SelectedVal
ue);
}
else
{
selectLanguage.Items.FindByValue(System.Threading.Thread.CurrentThrea
d.CurrentUICulture.TwoLetterISOLanguageName).Selected = true;
}
}

protected void selectLanguage_SelectedIndexChanged(object sender, EventArgs


e)
{
System.Threading.Thread.CurrentThread.CurrentUICulture =
System.Globalization.CultureInfo.CreateSpecificCulture(selectLanguage.SelectedVal
ue);
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Client Localization Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:DropDownList runat="server" AutoPostBack="true" ID="selectLanguage"
OnSelectedIndexChanged="selectLanguage_SelectedIndexChanged">
<asp:ListItem Text="English" Value="en"></asp:ListItem>
<asp:ListItem Text="Italian" Value="it"></asp:ListItem>
</asp:DropDownList>
<br /><br />
<asp:ScriptManager ID="ScriptManager1" EnableScriptLocalization="true"
runat="server">
<Scripts>
<asp:ScriptReference Assembly="LocalizingScriptResources"
Name="LocalizingScriptResources.CheckAnswer.js" />
</Scripts>
</asp:ScriptManager>
<div>
<Samples:ClientVerification runat="server" ></Samples:ClientVerification>
</div>
</form>
</body>
</html>

vb
<%@ Page Language="VB" AutoEventWireup="true" UICulture="auto" Culture="auto" %>
<%@ Register TagPrefix="Samples" Namespace="LocalizingScriptResources"
Assembly="LocalizingScriptResources" %>
<script runat="server">

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)


If (IsPostBack) Then
System.Threading.Thread.CurrentThread.CurrentUICulture =
System.Globalization.CultureInfo.CreateSpecificCulture(selectLanguage.SelectedVal
ue)
Else
selectLanguage.Items.FindByValue(System.Threading.Thread.CurrentThrea
d.CurrentUICulture.TwoLetterISOLanguageName).Selected = True
End If
End Sub

Protected Sub selectLanguage_SelectedIndexChanged(ByVal sender As Object,


ByVal e As EventArgs)
System.Threading.Thread.CurrentThread.CurrentUICulture =
System.Globalization.CultureInfo.CreateSpecificCulture(selectLanguage.SelectedVal
ue)
End Sub
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Client Localization Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:DropDownList runat="server" AutoPostBack="true" ID="selectLanguage"
OnSelectedIndexChanged="selectLanguage_SelectedIndexChanged">
<asp:ListItem Text="English" Value="en"></asp:ListItem>
<asp:ListItem Text="Italian" Value="it"></asp:ListItem>
</asp:DropDownList>
<br /><br />
<asp:ScriptManager ID="ScriptManager1" EnableScriptLocalization="true"
runat="server">
<Scripts>
<asp:ScriptReference Assembly="LocalizingScriptResources"
Name="LocalizingScriptResources.CheckAnswer.js" />
</Scripts>
</asp:ScriptManager>
<div>
<Samples:ClientVerification ID="ClientVerification1" runat="server"
></Samples:ClientVerification>
</div>
</form>
</body>
</html>

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.

8. Run the project.

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.

Das könnte Ihnen auch gefallen