【问题标题】:displayname attribute vs display attribute显示名称属性与显示属性
【发布时间】:2011-07-11 17:58:19
【问题描述】:

ASP.NET MVC 中DisplayName 属性和Display 属性有什么区别?

【问题讨论】:

    标签: c# asp.net-mvc data-annotations displayattribute .net-attributes


    【解决方案1】:

    DisplayName 在模型元数据中设置DisplayName。例如:

    [DisplayName("foo")]
    public string MyProperty { get; set; }
    

    如果您在视图中使用以下内容:

    @Html.LabelFor(x => x.MyProperty)
    

    它会生成:

    <label for="MyProperty">foo</label>
    

    Display 做同样的事情,但还允许您设置其他元数据属性,例如名称、描述、...

    Brad Wilson 的 nice blog post 涵盖了这些属性。

    【讨论】:

    • +1 - 可能比我的更有帮助(现已删除);早上对我来说太早了:)
    • 我在使用 PropertyDescriptor 和使用 Display(name.. 时遇到问题。当调用 @descriptor.DisplayName 时,它​​只能使用 DisplayName,而不是 Display(name..)。
    【解决方案2】:

    它们都给你相同的结果,但我看到的主要区别是你不能在DisplayName 属性中指定ResourceType。对于 MVC 2 中的示例,您必须继承 DisplayName 属性以通过本地化提供资源。 Display 属性(MVC3 和 .NET4 中的新特性)支持 ResourceType 重载作为“开箱即用”属性。

    【讨论】:

    • 很高兴知道!即将实现自定义属性以从 .resx 文件加载显示值,然后发生在这个问题上。显示属性是开发本地化应用程序时要走的路。
    【解决方案3】:

    我认为当前的答案忽略了突出实际重要和显着的差异以及这对预期用途意味着什么。虽然它们可能都在某些情况下工作,因为实施者内置了对两者的支持,但它们有不同的使用场景。两者都可以注释属性和方法,但这里有一些重要的区别:

    显示属性

    • System.ComponentModel.DataAnnotations.dll 程序集的System.ComponentModel.DataAnnotations 命名空间中定义
    • 可用于参数和字段
    • 允许您设置其他属性,例如DescriptionShortName
    • 可以使用资源进行本地化

    DisplayNameAttribute

    • DisplayName 位于System.dll 中的System.ComponentModel 命名空间中
    • 可用于课程和活动
    • 无法使用资源进行本地化

    程序集和命名空间说明了预期用途,并且本地化支持是最重要的。 DisplayNameAttribute 自 .NET 2 以来一直存在,似乎更多地用于命名遗留属性网格中的开发人员组件和属性,而不是用于可能需要本地化等的最终用户可见的东西。

    DisplayAttribute 后来在 .NET 4 中引入,似乎是专门为标记最终用户可见的数据类成员而设计的,因此它更适合 DTO、实体和其他此类事物。我觉得很遗憾,他们限制了它,所以它不能在课堂上使用。

    编辑:看起来最新的 .NET Core 源代码现在也允许在类上使用 DisplayAttribute

    【讨论】:

      【解决方案4】:

      也许这是特定于 .net 核心的,我发现 DisplayName 不起作用,但 Display(Name=...) 可以。这可能会节省其他人所涉及的故障排除:)

      //using statements
      using System;
      using System.ComponentModel.DataAnnotations;  //needed for Display annotation
      using System.ComponentModel;  //needed for DisplayName annotation
      
      public class Whatever
      {
          //Property
          [Display(Name ="Release Date")]
          public DateTime ReleaseDate { get; set; }
      }
      
      
      //cshtml file
      @Html.DisplayNameFor(model => model.ReleaseDate)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-05-23
        • 2017-04-02
        • 2017-04-21
        • 2013-06-23
        • 2017-11-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多