如何根据文化设置显示属性

How to set display attribute based on culture

我正在构建一个网站,其中包含更改显示语言的选项,这是在 URL 中确定的。

例如,如果我们导航到 http://website.com/en-US/ the page will be in english, and http://website.com/ru-RU,该网站将使用俄语。

你可以在下面看到我如何实现这个的细节。

我的问题是,我是否可以在 ViewModel 中检索此数据(保存在 PageData 中)以设置 Display 属性?或者我应该将此值设置为不同的变量(也许是会话?)如果是这样,我将如何检索它?

例如,我的 ViewModel 当前包含:

[Display(Name = "Email")]
public string Email { get; set; }

我需要类似的东西

[Display(Name = Resources.GetString("EmailDisplay", culture)]
public string Email { get; set; }

非常感谢您对此的帮助,谢谢!

RouteConfig.cs

routes.MapRoute(
    "Default",
    "{lang}/{controller}/{action}/{id}",
    new
    {
        lang = "ru-RU",
        controller = "Home",
        action = "Index",
        id = UrlParameter.Optional
    }
);

_ViewStart.cs

@{
    Layout = "~/Views/Shared/_Layout.cshtml";

    var cultureRoute = ViewContext.RouteData.Values["lang"].ToString();
    PageData["culture"] = new System.Globalization.CultureInfo(cultureRoute);
}

_Layout.cs

@{ 
    var culture = @PageData["culture"];
}

然后我有 2 个资源文件(Resources.en-US.resxResources.ru-RU.resx),我在页面上设置了元素的文本:

<h1>@Resources.ResourceManager.GetString("HomeTitle", culture)</h1>

感谢 Stephen 发布的 link,我能够通过首先在每个资源文件中添加所需的字符串来做到这一点。

这意味着将其添加到:

Resources.resx
Resources.en-US.resx
Resources.ru-RU.resx

然后将我的 ViewModel 属性 定义为:

[Display(Name = "LabelEmail", ResourceType = typeof(Resources))]
public string Email { get; set; }

最后,我更新了 _ViewStart.cs 以设置当前 UICulture(应用程序如何确定要使用哪个资源文件):

UICulture = cultureRoute;