是否可以使用具有强类型资源的LabelFor,ValidationMessageFor,EditorFor的数据注释?

Luk*_*Led 5 asp.net asp.net-mvc localization data-annotations asp.net-mvc-2

我想在我的ASP.NET MVC应用程序中使用DataAnnotations.我有强类型资源类,并希望在我的视图模型中定义:

[DisplayName(CTRes.UserName)]
string Username;
Run Code Online (Sandbox Code Playgroud)

CTRes是我的资源,自动生成类.不允许以上定义.还有其他解决方案吗?

Dar*_*rov 7

在.NET 4.0中添加了DisplayAttribute,允许您指定资源字符串:

[Display(Name = "UsernameField")]
string Username;
Run Code Online (Sandbox Code Playgroud)

如果您还不能使用.NET 4.0,那么您可以编写自己的属性:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以这样使用:

[Display(typeof(Resources.Resource), "UsernameField"),
string Username { get; set; }
Run Code Online (Sandbox Code Playgroud)


Ant*_*ton 0

属性不能做到这一点

从资源文件中查看C# 属性文本?

Resource.ResourceName 将是一个字符串属性,属性参数只能是常量、枚举、typeofs