Home How to set display attribute based on culture
Reply: 1

How to set display attribute based on culture

Bassie
1#
Bassie Published in 2017-09-14 10:24:03Z

I am building a website with the option to change the display language, where this is determined in the URL.

For example, if we navigate to http://website.com/en-US/ the page will be in english, and http://website.com/ru-RU the website will be in Russian.

You can see the details of how I implemented this below.

My question is, is it possible for me to retrieve this data (which is saved in PageData) in my ViewModel, to set the Display attribute? Or should I set this value to a different variable (perhaps session?) And if so, how would I go about retrieving it?

For example, where my ViewModel currently contains:

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

I need something like

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

Your help with this is much appreciated, thanks!

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"];
}

I then have 2 Resource files (Resources.en-US.resx and Resources.ru-RU.resx), and I set the text of elemnts on the page with:

<h1>@Resources.ResourceManager.GetString("HomeTitle", culture)</h1>
Bassie
2#
Bassie Reply to 2017-09-14 10:44:00Z

Thanks to the link posted by Stephen, I was able to do this by first adding the required string in each resource file.

This means adding it to:

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

And then defining my ViewModel property as:

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

Finally, I updated _ViewStart.cs to set the current UICulture (which is how the application determines which resources file to use):

UICulture = cultureRoute;
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.339304 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO