[原]ASP.NET MVC 3 Razor 多國語言參考解決方案 補充二

來源:互聯網
上載者:User

在上兩篇(1,2)中提到了如何在應用程式項目中使用資源檔的問題,還沒有測試在調用其他ClassLibrary中資源檔的情況,今早起來還按照以往ASP.NET項目中的作法做個測試

使用資源檔:

    public class Class1    {        public string GetTT()        {            return Resources.Test.TT;        }    }

期望能像往常一樣,隨著瀏覽器中的語言選項的變換能出現自動轉場效果,結果不出意料的失望了,只能顯示沒有帶Culture資訊的資源項值。

(3月22日重要更新內容:在web.config的system.web配置節點下加入<globalization culture="auto" uiCulture="auto"/>就可以不使用下列的方法了,唉,學藝不精啊!!!)

通過檢查資源檔的Designer.cs檔案,發現其內部有一個屬性定義:

        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]        internal static global::System.Globalization.CultureInfo Culture {            get {                return resourceCulture;            }            set {                resourceCulture = value;            }        }

於是猜想,如果能設定這個屬性值,想必可以讓ResourceManager自動選取相應的資源檔吧,但是添加在哪裡呢,發現在HttpApplication中有這樣一個事件:

public event EventHandler PreRequestHandlerExecute;

於是在Global裡面添加了這個事件的事件處理器,並在其方法內部添加如下代碼:

        protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)        {            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(Request.UserLanguages[0]);            Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;        }

F5運行,果然達到了預期的效果:隨著瀏覽器語言選項的切換,頁面上的語言也能自動切換了。

英文:

中文:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.