This walkthrough describes how to include an ECMAScript (JavaScript) file as an embedded resource in an assembly, and how to 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.
Prerequisites
To implement the procedures in this walkthrough you need:
- Visual Studio or Visual Web Developer 2010 Express.
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
- In Visual Studio, create a new class library project named LocalizingScriptResources.
- Add references to the System.Web and System.Web.Extensions assemblies to the project.
- Add a new JScript file to the project named CheckAnswer.js.
- Add the following code to the CheckAnswer.js file.
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 whether 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.
- In the Properties window for CheckAnswer.js, set Build Action to Embedded Resource.

- Add a class to the project named ClientVerification.
- Replace any code in the ClientVerification class file with the following code:
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);
}
}
}
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.
- Add a resources file to the project and name it VerificationResources.resx.
- Add a string resource named Correct with a value of "Yes, your answer is correct."
- Add a string resource named Incorrect with a value of "No, your answer is incorrect."
- 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.
- Save and close the VerificationResources.resx file.
- Add a resources file named VerificationResources.it.resx to the project.
This file will contain resource strings in Italian.
- Add a string resource named Correct with a value of "Si, la risposta e’ corretta."
- Add a string resource named Incorrect with a value of "No, la risposta e’ sbagliata."
- 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.
- Save and close the VerificationResources.it.resx file.
- Add the following line to the AssemblyInfo file. You can specify any name for the type name in the ScriptResourceAttribute attribute, but it must match the type name that is used in the client script. In this example, it is set to Answer.
[assembly: System.Web.UI.WebResource("LocalizingScriptResources.CheckAnswer.js", "application/x-javascript")]//用于下载js文件
[assembly: System.Web.UI.ScriptResource("LocalizingScriptResources.CheckAnswer.js", "LocalizingScriptResources.VerificationResources", "Answer")]//用于在脚本代码中使用资源(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 default namespace of the assembly and the name of the .js file. The ScriptResource definition does not include the file name extension or the localized .resx files.
- 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 walkthrough it is not assumed that you are doing this. 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 walkthrough. |
To reference the embedded script and resources
- In Visual Studio, create a new AJAX-enabled Web site.
- Add a Bin folder under the Web site root.
- Add the LocalizingScriptResources.dll assembly from the class library project to the Bin folder.
- Create a folder in the Bin folder and give it the name it (for Italian).
- Add the LocalizingScriptResources.resources.dll satellite assembly from the it folder in the LocalizingScriptResources project to the it folder in the Web site.
- Add a new ASP.NET Web page to the project.
- Replace the code in the page with the following code:
<%@ 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.SelectedValue);
}
else
{
try{
selectLanguage.Items.FindByValue(System.Threading.Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName).Selected = true;
}
catch{
selectLanguage.Items.FindByValue(“en”).Selected = true;
}
}
}
protected void selectLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.CreateSpecificCulture(selectLanguage.SelectedValue);
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html >
<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>
The control that you created in the LocalizingScriptResources project is included on the page. This control displays two numbers for the user to add and a TextBox control for the user to enter an answer. It also displays a button that calls the script in the CheckAnswer function when the button is clicked. The CheckAnswer function runs in the browser and displays a localized message that states 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 UI culture 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.
- 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 by selecting a language in the DropDownList control or by changing the preferred language in the browser.
Review
This walkthrough introduced the concept of embedding a JavaScript file as a resource in an assembly and of 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 on the language provided by the user.
Walkthrough: Adding Localized Resources to a JavaScript File
This walkthrough shows you how to include localized resources in an ECMAScript (JavaScript) file. In this walkthrough the resources are strings. You include localized resources in a JavaScript file when you have created a standalone JavaScript file and when your application must provide different values for different languages and cultures.
A standalone JavaScript is not embedded as a resource in an assembly and therefore cannot access values in a resources file. Instead, you include the localized string values directly in the script file. The localized values are retrieved when the script runs in the browser.
You create a separate script file for each supported language and culture. In each script file, you include an object in JSON format that contains the localized resources values for that language and culture.
Prerequisites
To implement the procedures in this tutorial you need:
- Visual Studio or Visual Web Developer 2010 Express.
- An AJAX-enabled ASP.NET Web site.
Creating a JavaScript File That Contains Localized Resource Values
To add resource values to a JavaScript file
- In the root directory of the Web site, add a folder named Scripts.
- In the Scripts folder, add a JScript file named CheckAnswer.js, and then add the following code to the file.
Sys.Application.add_load(SetButton);
function SetButton()
{
$get('Button1').value = Answer.Verify;
}
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;
}
}
Answer={
"Verify":"Verify Answer",
"Correct":"Yes, your answer is correct.",
"Incorrect":"No, your answer is incorrect."
};
The script code adds a handler for the load event of the Sys.Application class. The handler sets the button text. Instead of setting the text to a string, it sets the text to a value that is defined in a class named Answer.Verify. This enables the code to use a localized value.
The script also contains a function that checks the user's result for adding two numbers. It uses the alert function to let the user know whether the answer is correct. As with the button text, the message displayed in the alert dialog box is set to a localized string value without a postback to the server.
A type named Answer is used in the script to define the collection of localized values to use in the file. The Answer type is defined in JSON format at the end of the CheckAnswer.js file.
- In the Scripts folder, add a JScript file named CheckAnswer.it-IT.js. Add the following code to the file.
Sys.Application.add_load(SetButton);
function SetButton()
{
$get('Button1').value = Answer.Verify;
}
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;
}
}
Answer={
"Verify":"Verificare la risposta",
"Correct":"Si, la risposta e’ corretta.",
"Incorrect":"No, la risposta e’ sbagliata."
};
This file is identical to the CheckAnswer.js file except that it contains an Answer type with values in Italian.
To provide localized text in additional languages, you can create more JavaScript files. The JavaScript code is always the same, but the values that are defined in the Answer type are in different languages. The name of each JavaScript file must include the appropriate language and locale.
Using JavaScript Resource Values in an ASP.NET Page
You can now create an ASP.NET Web page that uses the script code that you have created. The page enables you to test the effect of changing a language.
To use JavaScript resource values in an ASP.NET Web page
- Create an ASP.NET Web page.
- Replace the content of the Web page with the following markup and code:
<%@ Page Language="C#" AutoEventWireup="true" UICulture="auto" Culture="auto" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
int _firstInt;
int _secondInt;
Random random = new Random();
_firstInt = random.Next(0, 20);
_secondInt = random.Next(0, 20);
firstNumber.Text = _firstInt.ToString();
secondNumber.Text = _secondInt.ToString();
if (IsPostBack)
{
userAnswer.Text = "";
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, EventArgs e)
{
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.CreateSpecificCulture(selectLanguage.SelectedValue);
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html >
<head id="Head1" runat="server">
<title>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="中D文?" Value="zh"></asp:ListItem>
<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 Path="scripts/CheckAnswer.js" ResourceUICultures="it-IT,zh-CN" />
</Scripts>
</asp:ScriptManager>
<div>
<asp:Label ID="firstNumber" runat="server"></asp:Label>
+
<asp:Label ID="secondNumber" runat="server"></asp:Label>
=
<asp:TextBox ID="userAnswer" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClientClick="return CheckAnswer()" />
<br />
<asp:Label ID="labeltest" runat="server"></asp:Label>
</div>
</form>
</body>
The markup creates a DropDownList control, two Label controls, a TextBox control, and a Button control. The page displays two randomly generated integers and asks the user to add them, and it provides a text box for an answer. When the button is clicked, the JavaScript CheckAnswer function is called.
The DropDownList control enables you 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.
The ScriptManager control includes a reference to the CheckAnswer.js script file. This causes the page to retrieve the CheckAnswer.js file when the page runs.
The ResourceUICultures property of the reference is set to "it-IT" to indicate that the Web site contains an Italian version of the script. As a result, the ScriptManager object retrieves the Italian version when you select "Italian" from the DropDownList control or when you set "Italian" as the default language in the browser.
- Run the page.
You see an addition problem with two randomly generated numbers and a TextBox control for entering an answer. When you type 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 is displayed in English.
- Change the language to Italian by selecting "Italian" from the drop-down list.
- Perform the quiz again.
This time, the answer is in Italian
Review
This walkthrough showed how to add localized resource values to a standalone JavaScript file. The localized values are created as objects in JSON format that are part of individual localized JavaScript files. Localized values are displayed by referencing the JSON object instead of by using hard-coded strings. The localized strings are displayed based on the language setting in the browser or on the language setting that is provided by the user.
Posted
2009/11/6 11:07
by
革命