Partager via


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:

  • Microsoft Visual Studio 2005 or Microsoft Visual Web Developer 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

  1. In the root directory of the Web site, add a folder named Scripts.

  2. 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."
    };
    
    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.

  3. 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."
    };
    
    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

  1. Create an ASP.NET Web page.

  2. Replace the content of the Web page with the following markup and code:

    <%@ Page Language="VB" AutoEventWireup="true" UICulture="auto" Culture="auto" %>
    
    <script runat="server">
    
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            Dim _firstInt As Int32
            Dim _secondInt As Int32
    
            Dim _random As New Random()
            _firstInt = _random.Next(0, 20)
            _secondInt = _random.Next(0, 20)
    
            firstNumber.Text = _firstInt.ToString()
            secondNumber.Text = _secondInt.ToString()
    
            If (IsPostBack) Then
                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
            End If
        End Sub
    
        Protected Sub selectLanguage_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
            System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.CreateSpecificCulture(selectLanguage.SelectedValue)
        End Sub
    </script>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>Client Localization Example</title>
    </head>
    <body>
        <form id="form1" runat="server" >
            <asp:DropDownList runat="server" AutoPostBack="true" ID="selectLanguage" OnSelectedIndexChanged="selectLanguage_SelectedIndexChanged">
                <asp:ListItem Text="English" Value="en"></asp:ListItem>
                <asp:ListItem Text="Italian" Value="it"></asp:ListItem>
            </asp:DropDownList>
            <br /><br />
            <asp:ScriptManager ID="ScriptManager1" EnableScriptLocalization="true" runat="server">
            <Scripts>
                <asp:ScriptReference Path="scripts/CheckAnswer.js" ResourceUICultures="it-IT" />
            </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>
    </html>
    
    <%@ 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 xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>Client Localization Example</title>
    </head>
    <body>
        <form id="form1" runat="server" >
            <asp:DropDownList runat="server" AutoPostBack="true" ID="selectLanguage" OnSelectedIndexChanged="selectLanguage_SelectedIndexChanged">
                <asp:ListItem Text="English" Value="en"></asp:ListItem>
                <asp:ListItem Text="Italian" Value="it"></asp:ListItem>
            </asp:DropDownList>
            <br /><br />
            <asp:ScriptManager ID="ScriptManager1" EnableScriptLocalization="true" runat="server">
            <Scripts>
                <asp:ScriptReference Path="scripts/CheckAnswer.js" ResourceUICultures="it-IT" />
            </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>
    </html>
    

    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.

    Note

    For information about how to set culture information for a thread, see How to: Set the Culture and UI Culture for ASP.NET Web Page Globalization.

    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.

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

  4. Change the language to Italian by selecting "Italian" from the drop-down list.

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

See Also

Tasks

Localizing Resources for Component Libraries Overview

Walkthrough: Embedding Localized Resources for a JavaScript File