ChatGPT解决这个技术问题 Extra ChatGPT

显示名称属性与显示属性

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


R
Richard Ev

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..)。
P
Pragmateek

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


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

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

显示属性

在 System.ComponentModel.DataAnnotations.dll 程序集的 System.ComponentModel.DataAnnotations 命名空间中定义

可用于参数和字段

允许您设置其他属性,例如 Description 或 ShortName

可以用资源本地化

显示名称属性

DisplayName 位于 System.dll 的 System.ComponentModel 命名空间中

可用于课程和活动

不能用资源本地化

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

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

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


m
mattpm

也许这是特定于 .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)