Why should I use LabelFor
instead of <label>
?
eg.
@Html.LabelFor(model => model.FirstName)
@Html.DisplayFor(model => model.FirstName)
vs
<label for="FirstName">First Name</label>
@Html.DisplayFor(model => model.FirstName)
Further to the above, @p.s.w.g has covered the DRY aspect of this question. I would also like to know if it helps with localization. ie. Different labels based on the current language setting.
Well, if you've decorated your models with the DisplayNameAttribute
like this:
[DisplayName("First Name")]
string FirstName { get; set; }
Then you only specify what the text of the label would be in one place. You might have to create a similar label in number of places, and if you ever needed to change the label's text it would be convenient to only do it once.
This is even more important if you want to localize your application for different languages, which you can do with the DisplayAttribute
:
[Display(Name = "FirstNameLabel", ResourceType = typeof(MyResources))]
string FirstName { get; set; }
It also means you'll have more strongly-typed views. It's easy to fat-finger a string like "FirstName"
if you have to type it a lot, but using the helper method will allow the compiler to catch such mistakes most of the time.