Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use LabelFor in MVC?

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.

like image 501
Jamie Avatar asked Oct 29 '13 23:10

Jamie


People also ask

How does HTML LabelFor work?

HTML label: Main Tips HTML label acts as a caption for a specified element. It is very convenient to use HTML label for <input> elements. It increases the clickable area, as clicking the label activates the input as well. An input element can also be nested inside the HTML label tag.

What is HTML ActionLink in MVC?

Html. ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.


2 Answers

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.

like image 142
p.s.w.g Avatar answered Oct 13 '22 22:10

p.s.w.g


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.

like image 35
webnoob Avatar answered Oct 14 '22 00:10

webnoob