逐步解說:嵌入已當地語系化的資源供 JavaScript 檔使用

更新:2007 年 11 月

本逐步解說說明如何將 ECMAScript (JavaScript) 檔納入組件中做為內嵌資源,以及如何包含當地語系化的字串,以便在 JavaScript 檔中使用。當您擁有必須隨組件散發的用戶端指令碼元件時,就需要將 JavaScript 檔嵌入組件。JavaScript 檔可從註冊組件的 Web 應用程式參考。當您必須修改用於不同語言與文化特性 (culture) 之 JavaScript 檔的值時,就需要嵌入當地語系化的資源。

必要條件

若要實作本逐步解說中的程序,您需要:

  • Microsoft Visual Studio 2008.

    注意事項:

    您不能使用 Visual Web Developer Express 版,因為 Visual Web Developer Express 版無法讓您建立逐步解說中所需的類別庫專案。

建立包含內嵌 JavaScript 檔的組件

一開始您會先建立包含要將其視為資源之 JavaScript 檔的組件 (.dll 檔案)。方式是在 Visual Studio 中建立類別程式庫專案,這樣會建立組件做為其輸出。

將用戶端指令碼檔案與資源嵌入組件中

  1. 在 Visual Studio 中,建立名為 LocalizingScriptResources 的新類別程式庫專案。

  2. 將 System.Web 和 System.Web.Extensions 組件的參考加入至專案。

  3. 將新的 JScript 檔加入至名為 CheckAnswer.js 的專案。

  4. 加入下列程式碼至 CheckAnswer.js 檔。

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

    程式碼會檢查使用者輸入的兩個數字相加的結果。它會使用 alert 函式讓使用者知道答案是否是正確的。在 alert 對話方塊顯示的訊息從當地語系化的資源讀取,未回傳至伺服器。

    在指令碼中會使用名為 Answer 的預留位置來識別哪些資源檔包含當地語系化字串。本程序稍後會定義 Answer 預留位置。

  5. 在 CheckAnswer.js 的 [屬性] 視窗中,將 [建置動作] 設定為 [內嵌資源]。

  6. 將類別加入至名為 ClientVerification 的專案。

  7. 使用下列程式碼取代 ClientVerification 類別檔案中的任何程式碼:

    Imports System.Web.UI
    Imports System.Web.UI.WebControls
    Imports System.Resources
    
    Public Class ClientVerification
        Inherits Control
    
        Private _button As Button
        Private _firstLabel As Label
        Private _secondLabel As Label
        Private _answer As TextBox
        Private _firstInt As Int32
        Private _secondInt As Int32
    
    
        Protected Overrides Sub CreateChildControls()
            Dim random = New Random()
            _firstInt = random.Next(0, 20)
            _secondInt = random.Next(0, 20)
    
            Dim rm = New ResourceManager("LocalizingScriptResources.VerificationResources", Me.GetType().Assembly)
            Controls.Clear()
    
            _firstLabel = New Label()
            _firstLabel.ID = "firstNumber"
            _firstLabel.Text = _firstInt.ToString()
    
            _secondLabel = New Label()
            _secondLabel.ID = "secondNumber"
            _secondLabel.Text = _secondInt.ToString()
    
            _answer = New TextBox()
            _answer.ID = "userAnswer"
    
            _button = New Button()
            _button.ID = "Button"
            _button.Text = rm.GetString("Verify")
            _button.OnClientClick = "return CheckAnswer();"
    
            Controls.Add(_firstLabel)
            Controls.Add(New LiteralControl(" + "))
            Controls.Add(_secondLabel)
            Controls.Add(New LiteralControl(" = "))
            Controls.Add(_answer)
            Controls.Add(_button)
        End Sub
    
    End Class
    
    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);
            }
        }
    }
    

    程式碼會建立自訂 ASP.NET 控制項。它包含兩個 Label 控制項、一個 TextBox 控制項,以及一個 Button 控制項。程式碼會顯示兩個隨機產生的整數,並提供文字方塊顯示解答。按一下該按鈕時,會呼叫 CheckAnswer 函式。

  8. 加入資源檔至專案,並將它命名為 VerificationResources.resx。

  9. 加入值為 "Yes, your answer is correct." 且名為 Correct 的字串資源。

  10. 加入值為 "No, your answer is incorrect." 且名為 Incorrect 的字串資源。

  11. 加入值為 "Verify Answer" 且名為 Verify 的字串資源。

    此資源不是使用用戶端指令碼來擷取。相反地,建立該按鈕時,會用它來設定 Button 控制項的 Text 屬性。

  12. 儲存並關閉 VerificationResources.resx 檔案。

  13. 加入名為 VerificationResources.it.resx 的資源檔至專案。

    此檔案將會包含義大利文的資源字串。

  14. 加入值為 "Si, la risposta e’ corretta." 且名為 Correct 的字串資源。

  15. 加入值為 "No, la risposta e’ sbagliata." 且名為 Incorrect 的字串資源。

  16. 加入值為 "Verificare la risposta" 且名為 Verify 的字串資源。

    如同以英文建立的 "Verify" 資源,此資源不是使用用戶端指令碼擷取。相反地,建立該按鈕時,會用它來設定 Button 控制項的 Text 屬性。

  17. 儲存並關閉 VerificationResources.it.resx 檔案。

  18. 將下列行加入至 AssemblyInfo 檔案。您可以在 ScriptResourceAttribute 屬性中指定任意的名稱當做型別名稱,但它必須符合用於用戶端指令碼中的型別名稱。在這個範例中,它是設定為 Answer。

    <Assembly: System.Web.UI.WebResource("LocalizingScriptResources.CheckAnswer.js", "application/x-javascript")> 
    <Assembly: System.Web.UI.ScriptResource("LocalizingScriptResources.CheckAnswer.js", "LocalizingScriptResources.VerificationResources", "Answer")> 
    
    [assembly: System.Web.UI.WebResource("LocalizingScriptResources.CheckAnswer.js", "application/x-javascript")]
    [assembly: System.Web.UI.ScriptResource("LocalizingScriptResources.CheckAnswer.js", "LocalizingScriptResources.VerificationResources", "Answer")]
    
    注意事項:

    AssemblyInfo.vb 檔案位於 [方案總管] 的 [我的專案] 節點內。如果您沒有在 [我的專案] 節點內看到任何檔案,請按一下 [專案] 功能表上的 [顯示所有檔案]。AssemblyInfo.cs 檔案位於 [方案總管] 的 [屬性] 節點內。

    WebResource 定義必須包含組件的預設命名空間以及 .js 檔案的名稱。ScriptResource 定義未包含副檔名或當地語系化的 .resx 檔案。

  19. 建置專案。

    編譯完成時,您會擁有名為 LocalizingScriptResources.dll 的組件。CheckAnswer.js 檔案中的 JavaScript 程式碼與兩個 .resx 檔案中的資源會嵌入此組件中做為資源。

    您也會擁有名為 LocalizingScriptResources.resources.dll 的組件 (附屬組件),它包含伺服端程式碼的義大利文資源。

參考內嵌指令碼與資源

現在您可以在具備 AJAX 能力的 ASP.NET 網站中使用該組件。您將能讀取 .js 檔案與用戶端指令碼中的資源值。

注意事項:

雖然您可以在相同的 Visual Studio 方案中建立類別庫專案與網站,但此逐步解說假設您不會這樣做。在不同的方案建立專案可模擬控制項開發人員與網頁開發人員獨立工作的情況。不過,為了方便起見,您可以在相同的方案中建立兩個專案,並稍微調整此逐步解說中的程序。

參考內嵌指令碼與資源

  1. 在 Visual Studio 中,建立具備 AJAX 能力的新網站。

  2. 在網站的根資料夾下加入 Bin 資料夾。

  3. 從類別程式庫專案加入 LocalizingScriptResources.dll 組件至 Bin 資料夾。

    注意事項:

    若在相同的 Visual Studio 方案中建立類別程式庫專案與網站,您可以從類別程式庫專案加入參考至網站。如需詳細資訊,請參閱 HOW TO:加入參考至網站中的 Visual Studio 專案

  4. 在 Bin 資料夾中建立資料夾,並將它命名為 it (用於義大利文)。

  5. 從 LocalizingScriptResources 專案的 it 資料夾加入 LocalizingScriptResources.resources.dll 附屬組件至網站的 it 資料夾。

  6. 加入新的 ASP.NET Web 網頁至專案。

  7. 使用下列程式碼取代網頁中的程式碼:

    <%@ Page Language="VB" AutoEventWireup="true" UICulture="auto" Culture="auto" %>
    <%@ Register TagPrefix="Samples" Namespace="LocalizingScriptResources" Assembly="LocalizingScriptResources" %>
    <script >
    
        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)
            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" >
        <title>Client Localization Example</title>
    </head>
    <body>
        <form id="form1" >
            <asp:DropDownList  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" >
            <Scripts>
                <asp:ScriptReference Assembly="LocalizingScriptResources" Name="LocalizingScriptResources.CheckAnswer.js" />
            </Scripts>
            </asp:ScriptManager>
            <div>
            <Samples:ClientVerification ID="ClientVerification1"  ></Samples:ClientVerification>
            </div>
        </form>
    </body>
    </html>
    
    <%@ Page Language="C#" AutoEventWireup="true" UICulture="auto" Culture="auto" %>
    <%@ Register TagPrefix="Samples" Namespace="LocalizingScriptResources" Assembly="LocalizingScriptResources" %>
    <script >
    
        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, 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 >
        <title>Client Localization Example</title>
    </head>
    <body>
        <form id="form1" >
            <asp:DropDownList  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" >
            <Scripts>
                <asp:ScriptReference Assembly="LocalizingScriptResources" Name="LocalizingScriptResources.CheckAnswer.js" />
            </Scripts>
            </asp:ScriptManager>
            <div>
            <Samples:ClientVerification  ></Samples:ClientVerification>
            </div>
        </form>
    </body>
    </html>
    

    您在 LocalizingScriptResources 專案中建立的控制項包含在網頁中。此控制項顯示兩個可讓使用者加入的號碼,以及可讓使用者輸入解答的 TextBox 控制項。它也會顯示一個按鈕,按下此按鈕時會呼叫 CheckAnswer 函式中的指令碼。CheckAnswer 函式會在瀏覽器中執行,並顯示當地語系化的訊息說明解答是否正確。

    您必須將 ScriptManager 物件的 EnableScriptLocalization 屬性設定為 true,以讓 ScriptManager 控制項擷取當地語系化的資源。您也必須將文化特性與 UI 文化特性設定為 "auto",以根據瀏覽器的設定顯示字串。

    網頁包含 DropDownList 控制項,可讓您在不需變更瀏覽器設定的情況下變更語言設定。當 DropDownList 控制項的 SelectedIndex 屬性變更時,CurrentThread 執行個體的 CurrentUICulture 屬性會設定為您選取的值。

  8. 執行專案。

    您也會看到一個加法問題 (含兩個隨機產生的號碼),以及一個可用於輸入解答的 TextBox 控制項。當您輸入答案並按一下 [Verify Answer] 按鈕時,會看到訊息視窗中的回應,告訴您答案是否正確。根據預設,回應以英文傳回。

    不過,若已將義大利文設定為瀏覽器的慣用語言,答案會以義大利文顯示。您可以在 DropDownList 控制項中選取語言,或變更瀏覽器的慣用語言,以變更回應的語言。

檢閱

本逐步解說介紹內嵌 JavaScript 檔做為組件資源,以及包含當地語系化字串的概念。內嵌的指令碼檔案可從包含組件的 Web 應用程式中參考與存取。當地語系化的字串將會根據瀏覽器的語言設定或使用者提供的語言顯示。

請參閱

工作

元件庫資源當地語系化概觀

逐步解說:將已當地語系化的資源加入至 JavaScript 檔