asp.net ajax and javascript

Upload: puspala-manojkumar

Post on 10-Apr-2018

244 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 ASP.net Ajax and Javascript

    1/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:

  • 8/8/2019 ASP.net Ajax and Javascript

    2/36

    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 theSys.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.registerNamespaceand .registerClassmethods.

    To enable ASP.NET AJAX functionality for an ASP.NET Web page, you must add an

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

    cs

    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() {

    http://ajax.asp.net/docs/ClientReference/Sys/EventHandlerListClass/default.aspxhttp://ajax.asp.net/docs/ClientReference/Sys/EventHandlerListClass/default.aspxhttp://ajax.asp.net/docs/ClientReference/Global/TypeClass/TypeRegisterNamespaceMethod.aspxhttp://ajax.asp.net/docs/ClientReference/Global/TypeClass/TypeRegisterNamespaceMethod.aspxhttp://ajax.asp.net/docs/ClientReference/Global/TypeClass/TypeRegisterClassMethod.aspxhttp://ajax.asp.net/docs/ClientReference/Global/TypeClass/TypeRegisterClassMethod.aspxhttp://ajax.asp.net/docs/ClientReference/Sys/EventHandlerListClass/default.aspxhttp://ajax.asp.net/docs/ClientReference/Global/TypeClass/TypeRegisterNamespaceMethod.aspxhttp://ajax.asp.net/docs/ClientReference/Global/TypeClass/TypeRegisterClassMethod.aspx
  • 8/8/2019 ASP.net Ajax and Javascript

    3/36

    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;

    },

    http://ajax.asp.net/docs/RunSample.aspx?sref=EnhancingJavaScript%23Namespace.aspxhttp://ajax.asp.net/docs/ViewSample.aspx?sref=EnhancingJavaScript%23Namespace.aspxhttp://ajax.asp.net/docs/RunSample.aspx?sref=EnhancingJavaScript%23Namespace.aspxhttp://ajax.asp.net/docs/ViewSample.aspx?sref=EnhancingJavaScript%23Namespace.aspx
  • 8/8/2019 ASP.net Ajax and Javascript

    4/36

    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

    http://ajax.asp.net/docs/RunSample.aspx?sref=EnhancingJavaScript%23Inheritance.aspxhttp://ajax.asp.net/docs/ViewSample.aspx?sref=EnhancingJavaScript%23Inheritance.aspxhttp://ajax.asp.net/docs/RunSample.aspx?sref=EnhancingJavaScript%23Inheritance.aspxhttp://ajax.asp.net/docs/ViewSample.aspx?sref=EnhancingJavaScript%23Inheritance.aspx
  • 8/8/2019 ASP.net Ajax and Javascript

    5/36

    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() {

  • 8/8/2019 ASP.net Ajax and Javascript

    6/36

    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

    EnumerationsAn 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,

    http://ajax.asp.net/docs/RunSample.aspx?sref=EnhancingJavaScript%23Interface.aspxhttp://ajax.asp.net/docs/ViewSample.aspx?sref=EnhancingJavaScript%23Interface.aspxhttp://ajax.asp.net/docs/ClientReference/Global/TypeClass/TypeRegisterEnumMethod.aspxhttp://ajax.asp.net/docs/RunSample.aspx?sref=EnhancingJavaScript%23Interface.aspxhttp://ajax.asp.net/docs/ViewSample.aspx?sref=EnhancingJavaScript%23Interface.aspxhttp://ajax.asp.net/docs/ClientReference/Global/TypeClass/TypeRegisterEnumMethod.aspx
  • 8/8/2019 ASP.net Ajax and Javascript

    7/36

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

    http://ajax.asp.net/docs/RunSample.aspx?sref=EnhancingJavaScript%23Enumeration.aspxhttp://ajax.asp.net/docs/ViewSample.aspx?sref=EnhancingJavaScript%23Enumeration.aspxhttp://ajax.asp.net/docs/ClientReference/Global/TypeClass/default.aspxhttp://ajax.asp.net/docs/ClientReference/Global/TypeClass/default.aspxhttp://ajax.asp.net/docs/RunSample.aspx?sref=EnhancingJavaScript%23Enumeration.aspxhttp://ajax.asp.net/docs/ViewSample.aspx?sref=EnhancingJavaScript%23Enumeration.aspxhttp://ajax.asp.net/docs/ClientReference/Global/TypeClass/default.aspx
  • 8/8/2019 ASP.net Ajax and Javascript

    8/36

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

    http://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/ClientReference/Global/TypeClass/default.aspxhttp://ajax.asp.net/docs/ClientReference/Global/TypeClass/default.aspxhttp://ajax.asp.net/docs/tutorials/EnhancingJavaScriptTutorial.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/ClientReference/Global/TypeClass/default.aspxhttp://ajax.asp.net/docs/tutorials/EnhancingJavaScriptTutorial.aspx
  • 8/8/2019 ASP.net Ajax and Javascript

    9/36

    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 Overviewand the Sys.Debug class overview.

    Component developers can create debug and retail versions of script files that are automatically

    managed by the ScriptManagercontrol. 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 ablock, as in the

    following example:

    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 aScriptReference object that

    points to the file question and that adds it to theScripts collection. The following example shows

    how to do this in markup:

    http://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/arrayTypeExt/default.aspxhttp://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/BooleanTypeExt/default.aspxhttp://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/DateTypeExt/default.aspxhttp://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/ErrorTypeExt/default.aspxhttp://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/NumberTypeExt/default.aspxhttp://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/ObjectTypeExt/default.aspxhttp://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/StringTypeExt/default.aspxhttp://ajax.asp.net/docs/ClientReference/Sys/DebugClass/default.aspxhttp://ajax.asp.net/docs/overview/ASPNETAJAXDebuggingAndTracingOverview.aspxhttp://ajax.asp.net/docs/overview/ASPNETAJAXDebuggingAndTracingOverview.aspxhttp://ajax.asp.net/docs/overview/ASPNETAJAXDebuggingAndTracingOverview.aspxhttp://ajax.asp.net/docs/ClientReference/Sys/DebugClass/default.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptReference.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptReference.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_Scripts.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_Scripts.aspxhttp://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/arrayTypeExt/default.aspxhttp://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/BooleanTypeExt/default.aspxhttp://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/DateTypeExt/default.aspxhttp://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/ErrorTypeExt/default.aspxhttp://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/NumberTypeExt/default.aspxhttp://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/ObjectTypeExt/default.aspxhttp://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/StringTypeExt/default.aspxhttp://ajax.asp.net/docs/ClientReference/Sys/DebugClass/default.aspxhttp://ajax.asp.net/docs/overview/ASPNETAJAXDebuggingAndTracingOverview.aspxhttp://ajax.asp.net/docs/overview/ASPNETAJAXDebuggingAndTracingOverview.aspxhttp://ajax.asp.net/docs/ClientReference/Sys/DebugClass/default.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptReference.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_Scripts.aspx
  • 8/8/2019 ASP.net Ajax and Javascript

    10/36

    For script files to be processed correctly by the ScriptManager control, each file must include a call

    to the Sys.Application.notifyScriptLoadedmethod at the end of the file. This call notifies theapplication 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 apath 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:

    noteThis scenario is not common for page developers, because most controls with embedded script

    libraries reference their scripts internally. For more information, seeEmbedding 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.

    http://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/ClientReference/Sys/ApplicationClass/SysApplicationNotifyScriptLoadedMethod.aspxhttp://ajax.asp.net/docs/ClientReference/Sys/ApplicationClass/SysApplicationNotifyScriptLoadedMethod.aspxhttp://ajax.asp.net/docs/tutorials/EmbedScriptFile.aspxhttp://ajax.asp.net/docs/tutorials/EmbedScriptFile.aspxhttp://ajax.asp.net/docs/tutorials/EmbedScriptFile.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_Scripts.aspxhttp://ajax.asp.net/docs/tutorials/assignScriptReferences.aspxhttp://ajax.asp.net/docs/tutorials/assignScriptReferences.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/O_T_System_Web_UI_ScriptManager_RegisterClientScriptBlock.aspxhttp://ajax.asp.net/docs/mref/O_T_System_Web_UI_ScriptManager_RegisterClientScriptInclude.aspxhttp://ajax.asp.net/docs/mref/O_T_System_Web_UI_ScriptManager_RegisterClientScriptResource.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/ClientReference/Sys/ApplicationClass/SysApplicationNotifyScriptLoadedMethod.aspxhttp://ajax.asp.net/docs/tutorials/EmbedScriptFile.aspxhttp://ajax.asp.net/docs/tutorials/EmbedScriptFile.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_Scripts.aspxhttp://ajax.asp.net/docs/tutorials/assignScriptReferences.aspxhttp://ajax.asp.net/docs/tutorials/assignScriptReferences.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/O_T_System_Web_UI_ScriptManager_RegisterClientScriptBlock.aspxhttp://ajax.asp.net/docs/mref/O_T_System_Web_UI_ScriptManager_RegisterClientScriptInclude.aspxhttp://ajax.asp.net/docs/mref/O_T_System_Web_UI_ScriptManager_RegisterClientScriptResource.aspx
  • 8/8/2019 ASP.net Ajax and Javascript

    11/36

    For a complete list of script-registration methods and their uses, see the ScriptManagercontrol

    overview.

    Any script blocks or inline script that you are registering must be inside the page'selement.

    Otherwise, the script is not registered with the ScriptManagercontrol and cannot access ASP.NET

    AJAX functionality. For more information, seeSys.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:

    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, seeAdding 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 theelement on the page, call the

    GetCurrent() method of theScriptManagercontrol to get the current instance of the control.

    http://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/ClientReference/Sys/ApplicationClass/SysApplicationInitializeMethod.aspxhttp://ajax.asp.net/docs/ClientReference/Sys/ApplicationClass/SysApplicationInitializeMethod.aspxhttp://ajax.asp.net/docs/tutorials/ExtenderControlTutorial1.aspxhttp://ajax.asp.net/docs/tutorials/ExtenderControlTutorial1.aspxhttp://ajax.asp.net/docs/ClientReference/Sys/ApplicationClass/SysApplicationNotifyScriptLoadedMethod.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/ClientReference/Sys/ApplicationClass/SysApplicationInitializeMethod.aspxhttp://ajax.asp.net/docs/tutorials/ExtenderControlTutorial1.aspxhttp://ajax.asp.net/docs/ClientReference/Sys/ApplicationClass/SysApplicationNotifyScriptLoadedMethod.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspx
  • 8/8/2019 ASP.net Ajax and Javascript

    12/36

    Test for null in case there is no ScriptManager control on the page. If you know that there is an

    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 aScriptManager 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 ThenThrow New Exception("ScriptManager not found.")

    Else : SMgr = ScriptManager.GetCurrent(Page)End If

    2. Create a ScriptReference object.

    CS

    ScriptReference SRef = new ScriptReference();

    VBDim SRef As ScriptReferenceSRef = 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";

    http://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://msdn2.microsoft.com/en-us/e1cwya7hhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptReference.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_ScriptPath.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptReference_Name.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptReference.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptReference_Path.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptReference.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://msdn2.microsoft.com/en-us/e1cwya7hhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptReference.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_ScriptPath.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptReference_Name.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptReference.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptReference_Path.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptReference.aspx
  • 8/8/2019 ASP.net Ajax and Javascript

    13/36

    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 Assemblyproperties 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 ScriptModeproperty of the ScriptManagercontrol. 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 ScriptReferenceobject is not set, the ScriptModeproperty of the

    ScriptManager control is set to Release by default. If the Path property of the ScriptReference

    http://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptReference_Name.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptReference_Assembly.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptReference_Assembly.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptReference.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_ScriptMode.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_ScriptMode.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptReference_ScriptMode.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptReference.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptReference.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptReference.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_ScriptMode.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_ScriptMode.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptReference_Path.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptReference.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptReference_Name.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptReference_Assembly.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptReference.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_ScriptMode.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptReference_ScriptMode.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptReference.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptReference.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_ScriptMode.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptReference_Path.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptReference.aspx
  • 8/8/2019 ASP.net Ajax and Javascript

    14/36

    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 Scriptscollection 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 theScriptManager 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 thelocaleFormatmethod. 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, seeASP.NET Globalization and Localization and the

    CultureInfo class overview.

    Prerequisites

    http://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_ScriptMode.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptReference.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_Scripts.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_Scripts.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/DateTypeExt/default.aspxhttp://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/DateTypeExt/DateLocaleFormatFunction.aspxhttp://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/DateTypeExt/DateLocaleFormatFunction.aspxhttp://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/DateTypeExt/DateLocaleFormatFunction.aspxhttp://ajax.asp.net/docs/ClientReference/Sys/CultureInfoClass/SysCultureInfoCurrentCultureProperty.aspxhttp://msdn2.microsoft.com/en-us/library/8ef3838e-9d05-4236-9dd0-ceecff9df80dhttp://msdn2.microsoft.com/en-us/library/8ef3838e-9d05-4236-9dd0-ceecff9df80dhttp://msdn2.microsoft.com/en-us/kx54z3k7http://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_ScriptMode.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptReference.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_Scripts.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/DateTypeExt/default.aspxhttp://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/DateTypeExt/DateLocaleFormatFunction.aspxhttp://ajax.asp.net/docs/ClientReference/Sys/CultureInfoClass/SysCultureInfoCurrentCultureProperty.aspxhttp://msdn2.microsoft.com/en-us/library/8ef3838e-9d05-4236-9dd0-ceecff9df80dhttp://msdn2.microsoft.com/en-us/kx54z3k7
  • 8/8/2019 ASP.net Ajax and Javascript

    15/36

    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 itsEnableScriptGlobalization property to true.

    note

    If the page does not contain aScriptManager 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.

    http://ajax.asp.net/docs/InstallingASPNETAJAX.aspxhttp://ajax.asp.net/docs/InstallingASPNETAJAX.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_EnableScriptGlobalization.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_EnableScriptGlobalization.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://ajax.asp.net/docs/InstallingASPNETAJAX.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_EnableScriptGlobalization.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspx
  • 8/8/2019 ASP.net Ajax and Javascript

    16/36

    8. Set the ChildrenAsTriggers property of the UpdatePanelcontrol tofalse.

    9. Set the UpdateMode property of theUpdatePanel control toConditional.

    10. Click inside the UpdatePanel control. Then in theStandard

    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 andButton controls inside theUpdatePanel 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

    theelement.

    http://ajax.asp.net/docs/mref/P_System_Web_UI_UpdatePanel_ChildrenAsTriggers.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_UpdatePanel_UpdateMode.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://msdn2.microsoft.com/en-us/3e83tsk6http://msdn2.microsoft.com/en-us/620f4seshttp://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://msdn2.microsoft.com/en-us/620f4seshttp://msdn2.microsoft.com/en-us/3e83tsk6http://msdn2.microsoft.com/en-us/3e83tsk6http://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/DateTypeExt/DateLocaleFormatFunction.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_UpdatePanel_ChildrenAsTriggers.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_UpdatePanel_UpdateMode.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://msdn2.microsoft.com/en-us/3e83tsk6http://msdn2.microsoft.com/en-us/620f4seshttp://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://msdn2.microsoft.com/en-us/620f4seshttp://msdn2.microsoft.com/en-us/3e83tsk6http://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://ajax.asp.net/docs/ClientReference/Global/JavascriptTypeExtensions/DateTypeExt/DateLocaleFormatFunction.aspx
  • 8/8/2019 ASP.net Ajax and Javascript

    17/36

    note

    The "auto" setting specifies that theACCEPT-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 theUpdatePanel 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

    theelement:

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

    Run View

    Globalizing a Date Based on Page Settings

    http://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://ajax.asp.net/docs/RunSample.aspx?sref=LocalizingDateTutorial1%23localeFormat.aspxhttp://ajax.asp.net/docs/ViewSample.aspx?sref=LocalizingDateTutorial1%23localeFormat.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://ajax.asp.net/docs/RunSample.aspx?sref=LocalizingDateTutorial2%23localeFormat.aspxhttp://ajax.asp.net/docs/ViewSample.aspx?sref=LocalizingDateTutorial2%23localeFormat.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://ajax.asp.net/docs/RunSample.aspx?sref=LocalizingDateTutorial1%23localeFormat.aspxhttp://ajax.asp.net/docs/ViewSample.aspx?sref=LocalizingDateTutorial1%23localeFormat.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://ajax.asp.net/docs/RunSample.aspx?sref=LocalizingDateTutorial2%23localeFormat.aspxhttp://ajax.asp.net/docs/ViewSample.aspx?sref=LocalizingDateTutorial2%23localeFormat.aspx
  • 8/8/2019 ASP.net Ajax and Javascript

    18/36

    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:

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

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

    http://msdn2.microsoft.com/en-us/library/f06cf9e5-22bb-461d-8b8f-549e53ff40a4http://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://ajax.asp.net/docs/RunSample.aspx?sref=LocalizingDateTutorial3%23localeFormat.aspxhttp://ajax.asp.net/docs/ViewSample.aspx?sref=LocalizingDateTutorial3%23localeFormat.aspxhttp://msdn2.microsoft.com/en-us/ms153472http://msdn2.microsoft.com/en-us/ms153472http://msdn2.microsoft.com/en-us/ms153472http://msdn2.microsoft.com/en-us/library/f06cf9e5-22bb-461d-8b8f-549e53ff40a4http://ajax.asp.net/docs/mref/T_System_Web_UI_UpdatePanel.aspxhttp://ajax.asp.net/docs/RunSample.aspx?sref=LocalizingDateTutorial3%23localeFormat.aspxhttp://ajax.asp.net/docs/ViewSample.aspx?sref=LocalizingDateTutorial3%23localeFormat.aspxhttp://msdn2.microsoft.com/en-us/ms153472http://msdn2.microsoft.com/en-us/ms153472http://msdn2.microsoft.com/en-us/ms153472
  • 8/8/2019 ASP.net Ajax and Javascript

    19/36

    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.

  • 8/8/2019 ASP.net Ajax and Javascript

    20/36

    Embedding a JavaScript File as a Resource in anAssembly

    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;

    }

    http://ajax.asp.net/docs/InstallingASPNETAJAX.aspxhttp://ajax.asp.net/docs/InstallingASPNETAJAX.aspxhttp://msdn2.microsoft.com/en-us/w7f1y429http://msdn2.microsoft.com/en-us/w7f1y429http://msdn2.microsoft.com/en-us/xs6ftd89http://ajax.asp.net/docs/InstallingASPNETAJAX.aspxhttp://msdn2.microsoft.com/en-us/w7f1y429http://msdn2.microsoft.com/en-us/xs6ftd89
  • 8/8/2019 ASP.net Ajax and Javascript

    21/36

    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:

  • 8/8/2019 ASP.net Ajax and Javascript

    22/36

    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()) {{

  • 8/8/2019 ASP.net Ajax and Javascript

    23/36

    {0}_borderAnimation.animate(panelElement);}}

    }})",

    updatePanel.ClientID,ColorTranslator.ToHtml(BorderColor));

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

    }}

    }}

    vb

    Imports System.Web.UIImports System.DrawingImports System.Globalization

    Public Class UpdatePanelAnimationWithClientResourceInherits Control

    Private _updatePanelID As StringPrivate _borderColor As ColorPrivate _animate As Boolean

    Public Property BorderColor() As ColorGet

    Return _borderColorEnd GetSet(ByVal value As Color)

    _borderColor = valueEnd Set

    End Property

    Public Property UpdatePanelID() As StringGet

    Return _updatePanelIDEnd GetSet(ByVal value As String)

    _updatePanelID = valueEnd Set

    End Property

    Public Property Animate() As BooleanGet

    Return _animate

    End GetSet(ByVal value As Boolean)

    _animate = valueEnd Set

    End Property

    Protected Overrides Sub OnPreRender(ByVal e As EventArgs)MyBase.OnPreRender(e)If (Animate) Then

  • 8/8/2019 ASP.net Ajax and Javascript

    24/36

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

    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 theProperties

    node of Solution Explorer.

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

    http://ajax.asp.net/docs/ClientReference/Sys/ApplicationClass/SysApplicationLoadEvent.aspxhttp://ajax.asp.net/docs/ClientReference/Sys/ApplicationClass/default.aspxhttp://ajax.asp.net/docs/ClientReference/Sys/ApplicationClass/SysApplicationLoadEvent.aspxhttp://ajax.asp.net/docs/ClientReference/Sys/ApplicationClass/default.aspx
  • 8/8/2019 ASP.net Ajax and Javascript

    25/36

    Referencing the Embedded Script File

    You will now reference the embedded script file in a Web application.

    noteAlthough 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 separatesolutions 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

    ScriptReference

    http://msdn2.microsoft.com/en-us/library/1886a4bb-c9d8-4ba6-8078-04bd02ab2179http://msdn2.microsoft.com/en-us/library/1886a4bb-c9d8-4ba6-8078-04bd02ab2179http://msdn2.microsoft.com/en-us/library/1886a4bb-c9d8-4ba6-8078-04bd02ab2179http://msdn2.microsoft.com/en-us/library/1886a4bb-c9d8-4ba6-8078-04bd02ab2179
  • 8/8/2019 ASP.net Ajax and Javascript

    26/36

    vb

    ScriptReference

  • 8/8/2019 ASP.net Ajax and Javascript

    27/36

    This code includes anelement 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, seeEmbed Localized Resources for a JavaScript File.

    http://ajax.asp.net/docs/tutorials/EmbedClientResources.aspxhttp://ajax.asp.net/docs/tutorials/EmbedClientResources.aspxhttp://ajax.asp.net/docs/tutorials/EmbedClientResources.aspx
  • 8/8/2019 ASP.net Ajax and Javascript

    28/36

    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.Weband 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(){

    http://ajax.asp.net/docs/InstallingASPNETAJAX.aspxhttp://ajax.asp.net/docs/InstallingASPNETAJAX.aspxhttp://msdn2.microsoft.com/en-us/w7f1y429http://msdn2.microsoft.com/en-us/w7f1y429http://ajax.asp.net/docs/InstallingASPNETAJAX.aspxhttp://msdn2.microsoft.com/en-us/w7f1y429
  • 8/8/2019 ASP.net Ajax and Javascript

    29/36

    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.

  • 8/8/2019 ASP.net Ajax and Javascript

    30/36

    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 = newResourceManager("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);

    }}

    }

  • 8/8/2019 ASP.net Ajax and Javascript

    31/36

    vb

    Imports System.Web.UIImports System.Web.UI.WebControlsImports System.Resources

    Public Class ClientVerification

    Inherits Control

    Private _button As ButtonPrivate _firstLabel As LabelPrivate _secondLabel As LabelPrivate _answer As TextBoxPrivate _firstInt As Int32Private _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."

    http://msdn2.microsoft.com/en-us/620f4seshttp://msdn2.microsoft.com/en-us/4b1xz97bhttp://msdn2.microsoft.com/en-us/3e83tsk6http://msdn2.microsoft.com/en-us/620f4seshttp://msdn2.microsoft.com/en-us/4b1xz97bhttp://msdn2.microsoft.com/en-us/3e83tsk6
  • 8/8/2019 ASP.net Ajax and Javascript

    32/36

  • 8/8/2019 ASP.net Ajax and Javascript

    33/36

    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.

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

    http://msdn2.microsoft.com/en-us/library/1886a4bb-c9d8-4ba6-8078-04bd02ab2179http://msdn2.microsoft.com/en-us/library/1886a4bb-c9d8-4ba6-8078-04bd02ab2179http://msdn2.microsoft.com/en-us/library/1886a4bb-c9d8-4ba6-8078-04bd02ab2179http://msdn2.microsoft.com/en-us/library/1886a4bb-c9d8-4ba6-8078-04bd02ab2179
  • 8/8/2019 ASP.net Ajax and Javascript

    34/36

    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

    protected void Page_Load(object sender, EventArgs e){

    if (IsPostBack){

    System.Threading.Thread.CurrentThread.CurrentUICulture =

    System.Globalization.CultureInfo.CreateSpecificCulture(selectLanguage.SelectedValue);}else{

    selectLanguage.Items.FindByValue(System.Threading.Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName).Selected = true;

    }}

    protected void selectLanguage_SelectedIndexChanged(object sender, EventArgse)

    {System.Threading.Thread.CurrentThread.CurrentUICulture =

    System.Globalization.CultureInfo.CreateSpecificCulture(selectLanguage.SelectedValue);

    }

    Client Localization Example



  • 8/8/2019 ASP.net Ajax and Javascript

    35/36

    vb

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

    ElseselectLanguage.Items.FindByValue(System.Threading.Thread.CurrentThrea

    d.CurrentUICulture.TwoLetterISOLanguageName).Selected = TrueEnd 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.SelectedValue)

    End Sub

    Client Localization Example



    The control that you created in the LocalizingScriptResources project is included on the page.

    This control displays two numbers to add, aTextBoxcontrol for the user to enter an answer, and

    a button that calls the script in the CheckAnswer function when it is clicked. The CheckAnswer

    http://msdn2.microsoft.com/en-us/4b1xz97bhttp://msdn2.microsoft.com/en-us/4b1xz97bhttp://msdn2.microsoft.com/en-us/4b1xz97bhttp://msdn2.microsoft.com/en-us/4b1xz97b
  • 8/8/2019 ASP.net Ajax and Javascript

    36/36

    function runs in the browser and displays a localized message that indicates whether the answer

    is correct.

    You must set the EnableScriptLocalizationproperty of the ScriptManagerobject 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 pagecontains a DropDownListcontrol 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, theCurrentUICulture 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 TextBoxcontrol

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

    http://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_EnableScriptLocalization.aspxhttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_EnableScriptLocalization.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://msdn2.microsoft.com/en-us/e0ybx34ehttp://msdn2.microsoft.com/en-us/e0ybx34ehttp://msdn2.microsoft.com/en-us/b3ffddfdhttp://msdn2.microsoft.com/en-us/e0ybx34ehttp://msdn2.microsoft.com/en-us/t733d0f8http://msdn2.microsoft.com/en-us/t733d0f8http://msdn2.microsoft.com/en-us/7y89f51whttp://msdn2.microsoft.com/en-us/4b1xz97bhttp://msdn2.microsoft.com/en-us/4b1xz97bhttp://msdn2.microsoft.com/en-us/4b1xz97bhttp://msdn2.microsoft.com/en-us/e0ybx34ehttp://msdn2.microsoft.com/en-us/e0ybx34ehttp://ajax.asp.net/docs/mref/P_System_Web_UI_ScriptManager_EnableScriptLocalization.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspxhttp://msdn2.microsoft.com/en-us/e0ybx34ehttp://msdn2.microsoft.com/en-us/b3ffddfdhttp://msdn2.microsoft.com/en-us/e0ybx34ehttp://msdn2.microsoft.com/en-us/t733d0f8http://msdn2.microsoft.com/en-us/7y89f51whttp://msdn2.microsoft.com/en-us/4b1xz97bhttp://msdn2.microsoft.com/en-us/e0ybx34e