關於在mvc4中多語言建站的實例


環境:vs2012 asp.net mvc4.

實現方式:resource 資源文件,根據路由規則中Lang參數來判斷載入哪種語言方式

在網上找到了相關資料,順便自己做了個練習,新建工程之類的步驟就免了,該注意的地方說明下,記着方便下次使用。

1:添加資源文件,記得設置資源文件的訪問模式為public,不然默認是Internal,外面會訪問不到:

 

 2:添加路由規則,記得加在Default路由規則的前面,否則新規則沒用,詳細原因請參考這篇文章

 1 routes.Add(new Route(
 2                 "{lang}/{controller}/{action}/{id}",
 3                 new RouteValueDictionary(new {
 4                     lang = "en-US",//默認為E文
 5                     controller = "Account",
 6                     action = "Logon",
 7                     id = UrlParameter.Optional
 8                 }),
 9                 new MultiLangRouteHandler()//這個類主要是通過GetHttpHandler來取得當前Lang的值
10             ));

 

 1 public class MultiLangRouteHandler : MvcRouteHandler {
 2         protected override IHttpHandler GetHttpHandler(RequestContext requestContext) {
 3             string lang = requestContext.RouteData.Values["lang"].ToString();
 4 
 5             //Thread.CurrentThread.CurrentCulture = new CultureInfo(lang);
 6             Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
 7 
 8             //return new MvcHandler(requestContext);
 9             return base.GetHttpHandler(requestContext);
10         }
11     }

有關代碼中的CurrentUICulture可以參考我上一篇文章,里面有詳細解釋。

 3:中英文切換入口。

1  <div>
2         @{
3             string controller = ViewContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();
4             string action = ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString();
5             //string lang = ViewContext.Controller.ValueProvider.GetValue("lang").RawValue.ToString();
6         }
7         @Html.ActionLink("中文", action, new { Controller = controller, lang = "zh-CN" }, new {@class="btn-a" })
8         @Html.ActionLink("English", action, new { Controller = controller, lang = "en-US" }, new {@class="btn-a" })
9     </div>

4:界面上普通文字的多語言

其實我有按照上面的那篇文章寫測試程序,但是寫死的資源文件並沒有根據中英文來切換,我都不知道是不是哪里有問題,悶~,后來mvc群里面的朋友(無情水)介紹另外一篇文章,我參照着改寫了下,在此說聲ths...

public static class LangHelper {
        //界面普通文字的多語言
        public static string GetLangbyKey(this HtmlHelper htmlhelper, string key) {
            Type resourceType = (Thread.CurrentThread.CurrentUICulture.Name == "en-US") ? typeof(Resources.en_US) : typeof(Resources.zh_CN);
            PropertyInfo p = resourceType.GetProperty(key);
            if (p != null)
                return p.GetValue(null, null).ToString();
            else
                return "undefined";
        }

        //js定義多語言彈出框
        public static string LangOutJsVar(this HtmlHelper htmlhelper, string key) {
            Type resourceType = (Thread.CurrentThread.CurrentUICulture.Name == "en-US") ? typeof(Resources.en_US) : typeof(Resources.zh_CN);
            PropertyInfo p = resourceType.GetProperty(key);
            if (p != null)
                return string.Format("var {0} = '{1}'", key, p.GetValue(null, null).ToString());
            else
                return string.Format("var {0} = '{1}'", key, "undefined");
        }
    }

View頁面調用直接用函數的方式。如:<h2>@Html.GetLangbyKey("LogonDisplay")</h2>

5:DisplayName 的多語言化

重新定義一LocalDisplayName屬性,他繼承自DisplayNameAttribute

public class LocalDisplayName : DisplayNameAttribute {
        private string _defaultName = "";
        public Type ResourceType {
            get { return (Thread.CurrentThread.CurrentUICulture.Name == "en-US") ? typeof(Resources.en_US) : typeof(Resources.zh_CN); }
        }
        public string ResourceName {
            get;
            set;
        }
        public LocalDisplayName(string defaultName) {
            _defaultName = defaultName;
        }
        public override string DisplayName {
            get {
                PropertyInfo p = ResourceType.GetProperty(ResourceName);
                if (p != null)
                    return p.GetValue(null, null).ToString();
                else
                    return _defaultName;
            }
        }
    }

在Model類上就把Display屬性換為LocalDisplayName

public class Account {
        [Required]
        [LocalDisplayName("user name", ResourceName = "UserDisplay")]
        public string UserName { get; set; }

        [Required]
        [LocalDisplayName("password", ResourceName = "PwdDisplay")]
        public string Pwd { get; set; }

        [Required]
        [Compare("Pwd",ErrorMessageResourceName="ConfirmPwdErrorDisplay")]
        [LocalDisplayName("confirm password", ResourceName = "ConfirmPwdDisplay")]
        public string ConfirmPwd { get; set; }
        
        [Required]
        [LocalDisplayName("remember", ResourceName = "RemDisplay")]
        public bool Rememberme { get; set; }

    }

調用方式:<div>@Html.LabelFor(m => m.UserName)</div>

 

實現效果:

 

大概這樣基本的就實現了, 有個Errormessage的還沒整好,有空再來寫。有不對的地方大家給予指正,謝謝!

參考文檔:

http://www.cnblogs.com/codehunter008/archive/2008/09/01/1281565.html

http://www.cnblogs.com/lionking/articles/1894277.html

如果是要寫數據庫的文字,應該怎么實現多語言呢?有什么好的方式,請教下。

下載鏈接: 點擊下載


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM