Why should I use LabelFor in MVC?

社会主义新天地 提交于 2019-12-10 12:28:05

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/19670798/why-should-i-use-labelfor-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!