Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# displayname属性与display属性_C#_Asp.net Mvc_Data Annotations_Displayattribute_.net Attributes - Fatal编程技术网

C# displayname属性与display属性

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

ASP.NET MVC中的
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
    命名空间中定义
  • 可用于参数和字段
  • 用于设置附加属性,如
    说明
    短名称
  • 可以使用资源进行本地化
DisplayNameAttribute

  • 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)