Reputation: 487
I am just extending my this question a bit.
I have my App_LocalResources in my MVC web application (I don't have it in separate dll).
I have a my Model in 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 an object of country as my viewmodel.
And in the view I use this:
@Html.LabelFor(mdl=>mdl.City.CityName)
@Html.LabelFor(mdl=>mdl.Cid)
So this works well and label with text are rendered in English.
But how do I modify this so that it reads the text from my Resource files in my web application?
Upvotes: 7
Views: 6208
Reputation: 209
You can also use translation with {0}, {2} parameters inside translation string. He is my example Localize Compare attribute
Upvotes: 0
Reputation: 4030
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 you want to reference. Use LabelFor as usual in your view, and it will automagically pull in your resource.
In my example, the label displays the string stored with the variable name AgreeTandCs, and if you're viewing it in English it will be shown in the page as "I agree to these Terms and Conditions".
Upvotes: 7
Reputation: 1039398
You could 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 may also checkout the following localization guide. It provides a full implementation of a sample attribute.
Upvotes: 14