I would like to use DataAnnotations in my ASP.NET MVC application. I have strongly typed resources class and would like to define in my view models:
[DisplayName(CTRes.UserName)]
string Username;
CTRes
is my resource, automatically generated class. Above definition is not allowed. Are there any other solutions?
There's the DisplayAttribute that has been added in .NET 4.0 which allows you to specify a resource string:
[Display(Name = "UsernameField")]
string Username;
If you can't use .NET 4.0 yet you may write your own attribute:
public class DisplayAttribute : DisplayNameAttribute
{
public DisplayAttribute(Type resourceManagerProvider, string resourceKey)
: base(LookupResource(resourceManagerProvider, resourceKey))
{
}
private static string LookupResource(Type resourceManagerProvider, string resourceKey)
{
var properties = resourceManagerProvider.GetProperties(
BindingFlags.Static | BindingFlags.NonPublic);
foreach (var staticProperty in properties)
{
if (staticProperty.PropertyType == typeof(ResourceManager))
{
var resourceManager = (ResourceManager)staticProperty
.GetValue(null, null);
return resourceManager.GetString(resourceKey);
}
}
return resourceKey;
}
}
which you could use like this:
[Display(typeof(Resources.Resource), "UsernameField"),
string Username { get; set; }
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