38

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.

tereško
  • 58,060
  • 25
  • 98
  • 150
Jamie
  • 779
  • 1
  • 9
  • 17

2 Answers2

51

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.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • 1
    Shouldn't the View - ViewModel relationship be one-to-one? In which case you'll still have to type it as many times whether it's in the View or the ViewModel. – Jamie Oct 29 '13 at 23:24
  • 3
    @Jamie It usually doesn't work out that way. For one thing, you'll probably have different views for displaying vs. editing the data. Plus, it's likely you'll need to throw a out `LabelFor` or `DisplayNameFor` for in other places throughout your app. – p.s.w.g Oct 29 '13 at 23:28
  • What is the advantage of using DisplayNameFor over LabelFor? – Jamie Oct 29 '13 at 23:37
  • 1
    @Jamie `DisplayNameFor` returns just the string rather than an HTML label. You'd need this, for example, if you want to put it in a `title` attribute when the user hovers over an element. – p.s.w.g Oct 29 '13 at 23:39
  • The only thing I don't like about this is I can never remember what the attribute name is. I don't use it enough so I have to google what it is every time. – Kellen Stuart Sep 15 '20 at 21:15
5

LabelFor allows you to control everything from your view model without worrying about the control.

Lets say you use the same view model in 2 places, this means you can change the name in one place to update all controls.

Doesn't have to be used, but it has its uses.

webnoob
  • 15,747
  • 13
  • 83
  • 165