ASP.NET MVC 多國語系

  • 135
  • 0

ASP.NET MVC 多國語系

參考連結:http://blog.miniasp.com/post/2011/09/07/App_GlobalResources-PublicResXFileCodeGenerator.aspx
屬性要記得調整,很重要( = 常常漏掉)所以特別強調:

  1. 「自訂工具」:PublicResXFileCodeGenerator
  2. 「建置動作」:內嵌資源

然後假設有資源檔:
Resource1.resx
Resource1.zh-TW.resx
Resource1.en-US.resx
只設定 "String1"分別為: "default", "zh-tw", "en-us"

controller

    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index(string cultureName = "")
        {
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName);
            Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;// 主要

            return View();
        }
    }

view

@{
    ViewBag.Title = "Index";
}

<p>GetString - @WebApplication2.Resource.Resource1.ResourceManager.GetString("String1")</p>
<p>String1 - @WebApplication2.Resource.Resource1.String1</p>

@{
    List<string> cultureList = new List<string> { "zh-tw", "en-US" };
    foreach (var culture in cultureList)
    {
        <a href="@Url.Action("Index", new { cultureName = culture })">@culture</a>
    }
}

CultureInfo列表:https://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(vs.71).aspx

大概就是這樣啦,剩下的事情…文字翻譯無關程式,翻譯後文字長度改變造成破版跟技術相關的部分就 css設個 min-width或 overflow: hidden之類的,跟政治角力與嘴炮功力反而比較有關。