【问题标题】:Is it possible to use data annotations for LabelFor,ValidationMessageFor, EditorFor with strongly typed resources?是否可以对具有强类型资源的 LabelFor、ValidationMessageFor、EditorFor 使用数据注释?
【发布时间】:2011-01-21 16:14:23
【问题描述】:

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

[DisplayName(CTRes.UserName)]
string Username;

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 这不允许使用类型的资源。 DisplayNameAttribute 是一个不好的例子,因为它也不允许使用弱类型:) 我的问题不是 DisplayName 不允许使用资源,因为正如您回答的那样,这很容易管理。我的问题是关于使用它们强类型,不仅与此属性一起使用,而且与 DataAnnotations 中的每个属性一起使用。
    • 这应该是“还有其他解决方案吗?”这个问题的公认答案。当前接受的答案只是“不,你不能”
    【解决方案2】:

    正如ScottGu's post 中所述,这现在可以在 MVC3 中正常工作,并且允许您将内置 DisplayAttribute 与本地化资源文件一起使用。

    【讨论】:

    • :) 这不是我需要的。当我写这个问题时,我没有注意到 DisplayName 属性不占用任何资源。我真正想要使用的是 strongly (ResourceClass.ResourceName) 类型的所有属性的资源。
    【解决方案3】:

    属性不能这样做

    C# attribute text from resource file?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-03
      • 1970-01-01
      • 2011-11-03
      • 1970-01-01
      • 2020-12-28
      • 1970-01-01
      • 2018-08-20
      • 2013-09-17
      相关资源
      最近更新 更多