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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With