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

时间:2010-02-26 23:22:11

标签: asp.net asp.net-mvc localization asp.net-mvc-2 data-annotations

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

[DisplayName(CTRes.UserName)]
string Username;

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

3 个答案:

答案 0 :(得分: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; }

答案 1 :(得分:0)

这在MVC3中应该正常工作,如ScottGu's post所述,并允许您使用内置的DisplayAttribute和本地化的资源文件。

答案 2 :(得分:0)

属性不能这样做

请参阅C# attribute text from resource file?

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

相关问题