【发布时间】:2011-07-11 17:58:19
【问题描述】:
ASP.NET MVC 中DisplayName 属性和Display 属性有什么区别?
【问题讨论】:
标签: c# asp.net-mvc data-annotations displayattribute .net-attributes
ASP.NET MVC 中DisplayName 属性和Display 属性有什么区别?
【问题讨论】:
标签: c# asp.net-mvc data-annotations displayattribute .net-attributes
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 涵盖了这些属性。
【讨论】:
它们都给你相同的结果,但我看到的主要区别是你不能在DisplayName 属性中指定ResourceType。对于 MVC 2 中的示例,您必须继承 DisplayName 属性以通过本地化提供资源。 Display 属性(MVC3 和 .NET4 中的新特性)支持 ResourceType 重载作为“开箱即用”属性。
【讨论】:
我认为当前的答案忽略了突出实际重要和显着的差异以及这对预期用途意味着什么。虽然它们可能都在某些情况下工作,因为实施者内置了对两者的支持,但它们有不同的使用场景。两者都可以注释属性和方法,但这里有一些重要的区别:
显示属性
System.ComponentModel.DataAnnotations.dll 程序集的System.ComponentModel.DataAnnotations 命名空间中定义Description 或ShortName
DisplayNameAttribute
System.dll 中的System.ComponentModel 命名空间中
程序集和命名空间说明了预期用途,并且本地化支持是最重要的。 DisplayNameAttribute 自 .NET 2 以来一直存在,似乎更多地用于命名遗留属性网格中的开发人员组件和属性,而不是用于可能需要本地化等的最终用户可见的东西。
DisplayAttribute 后来在 .NET 4 中引入,似乎是专门为标记最终用户可见的数据类成员而设计的,因此它更适合 DTO、实体和其他此类事物。我觉得很遗憾,他们限制了它,所以它不能在课堂上使用。
编辑:看起来最新的 .NET Core 源代码现在也允许在类上使用 DisplayAttribute。
【讨论】:
也许这是特定于 .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)
【讨论】: