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?

Answers


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


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; }

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.


Need Your Help

Domain Redirect

redirect dns

I have domain for ex. example.com. That domain blocked in malaysia. So i am planning to redirect example.com to example.my only for malaysian user. I know how to redirect domain using php, javascript

For each table row / cell with specific class function: Javascript - jQuery

javascript jquery jquery-selectors

I have a table. The table has some set of rows, each set containing 3 specific rows, and repeated downwards.. I want to have a variable i which should be incremented for each row (<tr>) having

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.