Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use data annotations for LabelFor,ValidationMessageFor, EditorFor with strongly typed resources?

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?

like image 519
LukLed Avatar asked Feb 26 '10 23:02

LukLed


1 Answers

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; }
like image 120
Darin Dimitrov Avatar answered Sep 23 '22 13:09

Darin Dimitrov