C# displayname属性与display属性
ASP.NET MVC中的C# displayname属性与display属性,c#,asp.net-mvc,data-annotations,displayattribute,.net-attributes,C#,Asp.net Mvc,Data Annotations,Displayattribute,.net Attributes,ASP.NET MVC中的DisplayName属性和Display属性之间有什么区别?DisplayName设置模型元数据中的DisplayName。例如: [DisplayName("foo")] public string MyProperty { get; set; } 如果您在视图中使用以下内容: @Html.LabelFor(x => x.MyProperty) 它将产生: <label for="MyProperty">foo</label> f
DisplayName
属性和Display
属性之间有什么区别?DisplayName
设置模型元数据中的DisplayName
。例如:
[DisplayName("foo")]
public string MyProperty { get; set; }
如果您在视图中使用以下内容:
@Html.LabelFor(x => x.MyProperty)
它将产生:
<label for="MyProperty">foo</label>
foo
Display
执行相同的操作,但也允许您设置其他元数据属性,如名称、说明等
Brad Wilson有一个覆盖这些属性的方法。它们都提供相同的结果,但我看到的关键区别是,您不能在
DisplayName
属性中指定ResourceType
。例如,在MVC2中,您必须对DisplayName
属性进行子类化,以便通过本地化提供资源Display
属性(MVC3和.NET4中新增)支持将ResourceType
重载作为“开箱即用”属性。我认为当前的答案忽略了强调实际的重要差异以及这对预期用途的意义。虽然它们可能都在某些情况下工作,因为实现者内置了对两者的支持,但它们有不同的使用场景。两者都可以注释属性和方法,但以下是一些重要的区别:
DisplayAttribute
- 在
程序集中的System.ComponentModel.DataAnnotations.dll
命名空间中定义System.ComponentModel.DataAnnotations
- 可用于参数和字段
- 用于设置附加属性,如
或说明
短名称
- 可以使用资源进行本地化
- DisplayName位于
System.dll中的
命名空间中System.ComponentModel
- 可用于类和事件
- 无法使用资源进行本地化
DisplayNameAttribute
自.NET 2以来就一直存在,似乎更多地用于在传统属性网格中命名开发人员组件和属性,而不是用于最终用户可能需要本地化等可见的内容
DisplayAttribute
后来在.NET 4中引入,似乎是专门为标记最终用户可见的数据类成员而设计的,因此它更适合于DTO、实体和其他类似的东西。我觉得很不幸,他们限制了它,所以不能在课堂上使用
编辑:看起来最新的.NET Core源代码也允许在类上使用
DisplayAttribute
。也许这是特定于.NET Core的,我发现DisplayName不起作用,但Display(Name=…)起作用。这可能会为其他人节省所涉及的疑难解答:)
+1-可能比我的有用得多(现已删除);早上对我来说太早了:)我在PropertyDescriptor和使用Display(name..时遇到问题。调用@descriptor.DisplayName时,它只能使用DisplayName而不能使用Display(name..)。很高兴知道!即将实现一个自定义属性以从.resx文件加载显示值,然后出现了这个问题。在开发本地化应用程序时,显示属性是一种方法。
//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)