LocalizedDisplayNameAttribute class for Asp.Net MVC2

For whatever reason, in MVC2 the DisplayName attribute isn't localizable in the way that ValidationAttributes are - it doesn't have a constructor that looks up resources.

So here's how to localise DisplayName:

public class LocalizedDisplayNameAttribute : DisplayNameAttribute
{
    public LocalizedDisplayNameAttribute(Type resourceType, string resourceKey) : base(LookupResource(resourceType, resourceKey)) {  }
    public LocalizedDisplayNameAttribute(Type resourceType) : base(LookupResource(resourceType, DisplayNameAttribute.Default.DisplayName) ) { }

    internal static string LookupResource(Type resourceType, string resourceKey)
    {
        return new ResourceManager(resourceType).GetString(resourceKey) ?? resourceKey;
    }
}

Note! This will all fail dismally unless ... your resource file is marked as public, rather than internal. Because Views are not compiled as part of the web project assembly, rather they are compiled at runtime by the asp.net compiler into a different assembly

LocalizedDisplayNameAttribute class for …

by Chris F Carroll read it in 1 min
0