开发者

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 开发者_如何学Pythonmodels:

[DisplayName(CTRes.UserName)]
string Username;

CTRes is my resource, automatically generated class. Above definition is not allowed. Are there any other solutions?


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜