displayname属性vs display属性

Gho*_*ngi 122 c# asp.net-mvc data-annotations displayattribute .net-attributes

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

Dar*_*rov 140

DisplayName设置DisplayName模型元数据.例如:

[DisplayName("foo")]
public string MyProperty { get; set; }
Run Code Online (Sandbox Code Playgroud)

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

@Html.LabelFor(x => x.MyProperty)
Run Code Online (Sandbox Code Playgroud)

它会产生:

<label for="MyProperty">foo</label>
Run Code Online (Sandbox Code Playgroud)

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

Brad Wilson有一篇很好的博客文章,涵盖了这些属性.


Spo*_*ock 68

它们都给你相同的结果,但我看到的关键区别是你不能指定ResourceTypein DisplayName属性.对于MVC 2中的示例,您必须子类化该DisplayName属性以通过本地化提供资源.Display属性(MVC3和.NET4中的新增属性)支持ResourceType重载作为"开箱即用"属性.


Mik*_*ski 20

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

DisplayAttribute

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

DisplayNameAttribute

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

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

DisplayAttribute稍后在.NET 4中引入,似乎专门用于标记最终用户可见的数据类成员,因此它更适合DTO,实体和其他类似的东西.我发现相当不幸的是他们限制了它,所以它不能在课堂上使用.

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


mat*_*tpm 11

也许这是特定于.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)
Run Code Online (Sandbox Code Playgroud)