views:

456

answers:

2

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?

+2  A: 

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; }
Darin Dimitrov
That doesn't allow to use **strongly** typed resources. DisplayNameAttribute was bad example, because it doesn't allow using weakly typed too:) My question is not about DisplayName not allowing to use resources, because, as you answered, this can be easily managed. My question is about using them **strongly typed** and not only with this attribute, but with every attribute in DataAnnotations.
LukLed
A: 

This now works as it should in MVC3, as mentioned on ScottGu's post, and would allow you to use the built in DisplayAttribute with a localized resource file.

thekaido
:) That is not what I need. When I wrote this question, I didn't notice that DisplayName attribute doesn't take any resources. What I really want to use is **strongly** (`ResourceClass.ResourceName`) typed resouces with all attributes.
LukLed