How to do localization for content coming from @ Html.LabelFor () in mvc3

I am expanding my question a bit.

I have my App_LocalResources in my MVC web application (I don't have it in a separate dll).

I have my Model in a different assembly. In the model, I have 2 classes Country and City :

 public class Country: MyContainer { public City city {get;set;} } public class City { public CityName {get;set;} } public class MyContainer { public Cid {get;set;} } 

So, in my action method, I create and pass the country object as my view model.

And in the view, I use this:

 @Html.LabelFor(mdl=>mdl.City.CityName) @Html.LabelFor(mdl=>mdl.Cid) 

So this works well, and the label with the text is displayed in English.

But how can I change this so that it reads text from my resource files in my web application?

+7
source share
3 answers

You can write a custom display attribute:

 public class LocalizedDisplayNameAttribute : DisplayNameAttribute { public LocalizedDisplayNameAttribute(string key): base(FormatMessage(key)) { } private static string FormatMessage(string key) { // TODO: fetch the corresponding string from your resource file throw new NotImplementedException(); } } 

and then:

 public class City { [LocalizedDisplayName("cityname")] public string CityName { get; set; } } 

You can also check the following localization guide . It provides full implementation of the sample attribute.

+12
source

You can use [Display(ResourceType = typeof(App_LocalResources), Name = "AgreeTandCs")] , where App_LocalResources is the name of the resource class (your .resx ), and Name is the name of the static string that you want to reference. Use LabelFor, as usual, in your opinion, and it will automatically draw your resource.

In my example, the label displays the string stored with the variable name AgreeTandCs, and if you view it in English, it will be displayed on the page as "I agree to these Terms of Use."

+3
source

You can also use a translation with {0}, {2} parameters inside the translation string. He is my example. Localize Compare Attribute

0
source

All Articles