0

To my knowledge the html helper method DisplayNameFor will take the value set in Display attributed decorating the property in the expression passed to it, so for example for the following property.

[Display(Name = "Name", ResourceType = typeof(Resource))]
public string Name { get; set; }

If you have Resource entry as follows

Name: First Name

If you use DisplayNameFor as follows

@Html.DisplayNameFor(x => x.Name)

The displayed value will be

First Name

My question is, why don't you use the reference to the resource directly in razor so instead of using the DisplayNameFor method, you just use the follow

@Resource.Name

In my opinion this is even better because it doesn't have the risk of magic strings used in the Display attribute. So what value does DisplayNameFor add to my code? and why should I use it?

Sisyphus
  • 900
  • 12
  • 32
  • I think it is for localization. – Mustafa Çetin Mar 27 '18 at 16:00
  • Localization of DisplayNameAttribute: https://stackoverflow.com/questions/356464/localization-of-displaynameattribute – Vince Mar 27 '18 at 16:01
  • Yes I understand this, I have already mentioned this in the question, if it for localization, why don't we just write `@Resource.Name` instead of the `DisplayNameFor` , and avoid the risk of using magic strings the the `Display` attribute. – Sisyphus Mar 27 '18 at 16:08
  • To avoid the use of the Display name attribute at all (and no magic strings), you can extend the framework - http://www.michael-whelan.net/using-humanizer-with-asp-dotnet-core/ That is .NET Core, but there is a way of doing it for MVC 5 as well. Inherit from DataAnnotationsModelMetadataProvider. Google that. – onefootswill Mar 27 '18 at 22:02

0 Answers0