在视图中使用名称数据注释与硬编码

Using the name data annotation vs hard coding in view

我的 EntityFramework 域模型中有以下内容:

[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }

[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }

在我看来,我做了以下事情:

@Html.LabelFor(model => model.FirstName)

但我想知道,为什么最好在我的模型中指定 "Display Name" 而不是在视图页面中手动编写标签?

我实际上可以看到这会导致更多问题,如果 6 个月后有人来找我说 "We don't want it to say First Name anymore, we want it to say "你的名字”,我要么不得不恢复硬编码,要么重新编译我的模型项目以使更改生效..

使用数据注释有什么我不知道的好处吗?

DisplayAttribute 的好处是本地化,如下面的代码。

[Required]
[Display(Name = "First Name", ResourceType = typeof(YourResources)))]
public string FirstName { get; set; }

ASP.NET MVC 3 localization with DisplayAttribute and custom resource provider 对本地化和实现本地化的不同方法有一些很好的回答。

好处简直DRY.

因此您目前只在一个地方使用它,即您的编辑页面。现在添加:

  • 多个验证消息(需要名字等)
  • 查看(只读)页面
  • 一个列表页面
  • 摘要/工具提示
  • 另一页的引用
  • logging/tracing
  • 一个面包屑(好吧,把它推到这里)

现在您必须在 15 个以上的地方进行更改,遗漏一个的可能性...高
[其中一个或多个打字错误的可能性......不低]

因此,在您使用的每一个中都引用 DisplayName 而不是手动输入...现在您只需更改...1 个地方。