Reputation: 5705
not sure why, but the data annotation in MVC3 insist on having constant values, which i just can't understand for things like error messages and display names. I love these annotations, they are so easy to use and so powerful, but what if you need to support multiple languages?
Imagine i have the following model:
public class Person
{
public string First_Name { get; set; }
}
If i dont change anything and use the CRUD views that MVC3 will build for me I get a label next to the text fields that says "First_Name", so i add the data annotation to change the display name like so:
public class Person
{
[Display(Name="First name")]
public string First_Name { get; set; }
}
Which works just fine. But i want to supply a different display name depending on the users language, using a function i made previously GetDisplayName(string ToGet, string Language)
which just returns the string i am interested in, but if i change my data annotation to this:
public class Person
{
[Display(Name=GetDisplayName("First_Name", "English"))]
public string First_Name { get; set; }
}
Then i get a compiler error telling me that the annotation requires a constant values, WHY????
Does anyone know a way to accomplish what i am trying to do? Thanks
UPDATE
Ok, it appears that the best way to do this is with .resx
resource files as per several answers below and those in other posts. which works great for the most part.
Does anyone know how i can request a resource with a variable name? not in the context of data attributes this time, but just in controllers and views.
Basically at the moment i am getting at the resources with @Resources.SomeKey
but i would like to be able to use that within a function in a @Resources["SomeOtherKey"]
where SomeOtherKey
is a dynamically generated string.
Upvotes: 4
Views: 6541
Reputation: 309
You can only assign constants.
You can do an extension and assign keyValues there and then the extension fetches from somewhere else, like a database or a resource file or a webservice or whatever.
Upvotes: 1
Reputation: 1
[Display(Name = "strResourceString", ResourceType = typeof(Resourcefile.strResourceString))]
Upvotes: -1
Reputation: 14133
If you have your translated property names in Resource Files, that is supported out of the box... no need to extend the framework.
Just use:
[Display(Name = "Resource_Key", ResourceType = typeof(DataFieldLabels))]
public string myProperty { get; set; }
Where the "Resource_Key" is the key in your resource files... and the "DataFieldLabels" is the name of your base resource file.
EDIT:
In order to access resource files dynamically you can do:
ResourceSet resset = ResourceManager.GetResourceSet(culture, true, false);
var translated = resset.GetString("myToken")
Upvotes: 7
Reputation: 2121
DataAnnotations param values require constants, i.e. actual strings.
Upvotes: 1
Reputation: 5286
You may want to check Hanselman's post regarding internationalization. Maybe it could help
Upvotes: 0