【问题标题】:Localization in MVC 5 - How can I render multi-lingual text in my view using a resource file?MVC 5 中的本地化 - 如何使用资源文件在视图中呈现多语言文本?
【发布时间】:2016-11-13 08:39:18
【问题描述】:

我正在尝试在 MVC 5 应用程序中创建多语言导航。

我做了什么:

  1. 根据 cookie 值将System.Threading.Thread.CurrentThread.CurrentUICulture 设置为“en-US”或“es-ES”(默认为英文 除非用户选择西班牙语)
  2. 创建了三个资源文件(这是我第一次使用它们,所以我不确定我是否完全理解这个概念......)Index.resx、Resouce.en-US.resx、Resouce.es- ES.resx。每个资源文件都在一个名为 App_GlobalResources 文件夹的文件夹中

  3. 为每个 .resx 文件添加了名称/值组合,Home/Home 用于 Index.resx 和 en-US.resx,Home/Casa 用于 es-ES.resx

  4. 尝试在我的布局文件中使用@Resources.Index.Home,认为当CurrentUICulture 的值从en-US 更改为es-ES 和反之亦然时,语言会根据我的资源文件中的值而改变。

有人可以告诉我,当值CurrentUICulture 为“es-ES”时如何获取西班牙语文本,当值为“en-US”时如何获取英文文本?

_Layout.cshtml

Resource.resx

编辑

我应该说 - @Resources.Index.Home 确实在导航中呈现文本“Home”。但是,当我将CurrentUICulture 切换到“es-ES”时,它仍然呈现“Home”,而不是“Casa”

编辑 2

这是我如何设置 CurrentUICulture 是 global.asax

   public void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            if (Request.Cookies["lang"] == null)
            {
                HttpCookie lang = new HttpCookie("lang");
                lang.Value = "english";
                lang.Expires = DateTime.Now.AddDays(30d);
                Response.Cookies.Add(lang);
            }
            else if (Request.Cookies["lang"] != null)
            {
                if (Request.Cookies["lang"].Value != null && Request.Cookies["lang"].Value == "english")
                {
                    System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-us");
                }
                else if (Request.Cookies["lang"].Value != null && Request.Cookies["lang"].Value == "spanish")
                {
                    System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-es");
                }
            }
        }

【问题讨论】:

  • 它应该可以工作,你有任何错误信息吗?你能发布你的控制器如何初始化你的 CurrentUICulture 吗?你在 @Resources.Index.Home 有什么?它显示什么吗?
  • 谢谢 - 好点 - 没有错误。请看我的更新。 @Resources.Index.Home 确实呈现文本“Home”,但是当 CurrentUICulture 设置为“es-ES”时它不会更改为“Casa”
  • 你能把你初始化 CurrentUICulture 的代码贴出来
  • @Yanga 刚刚发布。
  • 您是否尝试强制文化,只需添加例如 System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-es");在 Application_AuthenticateRequest 的末尾(在“if”、“else if”代码之后)

标签: c# asp.net asp.net-mvc-5


【解决方案1】:

只需尝试将@Resources.Index.Home 替换为@Resources.Home
这是您对本地化的理解。
每个具有本地化功能的应用程序(比如 N 种文化)都必须有 N 个.resx-文件,其名称相同,但后缀不同。 + 默认区域性可以不带后缀使用。 所以你有 2 种文化 - 你必须使用 2 个 .resx 文件,而不是更多。所以Index.resx 根本不需要。
这应该有效。如果没有,更多修复:
- 不要使用 App_GlobalResources 文件夹。只需在常用项目文件夹或项目根文件夹中创建 .resx,就像在桌面 .NET 应用程序中一样。
这对我有帮助,希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    • 2013-05-01
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多