5

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

[DisplayName(CTRes.UserName)]
string Username;

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

4

3 回答 3

7

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

[Display(Name = "UsernameField")]
string Username;

如果您还不能使用 .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;
    }
}

你可以这样使用:

[Display(typeof(Resources.Resource), "UsernameField"),
string Username { get; set; }
于 2010-02-27T10:03:38.260 回答
0

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.

于 2010-08-06T20:46:12.933 回答
0

属性不能这样做

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

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

于 2011-02-03T15:42:08.307 回答