5

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?

LukLed
  • 31,452
  • 17
  • 82
  • 107

3 Answers3

7

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
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    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 Mar 04 '10 at 01:55
  • This should be the accepted answer to the question "Are there any other solutions?". The current accepted answer is simply "No you can't" – Typo Johnson Apr 16 '13 at 13:42
0

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.

bkaid
  • 51,465
  • 22
  • 112
  • 128
  • :) 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 Aug 06 '10 at 23:30
0

Attributes can't do this

see C# attribute text from resource file?

Resource.ResourceName would be a string property, attribute parameters can only be constants, enums, typeofs

Community
  • 1
  • 1
Anthony Johnston
  • 9,405
  • 4
  • 46
  • 57