asp.net-mvc 为什么要在 MVC 中使用 LabelFor?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19670798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why should I use LabelFor in MVC?
提问by Jamie
Why should I use LabelForinstead of <label>?
为什么我应该使用LabelFor而不是<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.
除上述内容外,@pswg 还涵盖了此问题的 DRY 方面。我也想知道它是否有助于本地化。IE。基于当前语言设置的不同标签。
回答by p.s.w.g
Well, if you've decorated your models with the DisplayNameAttributelike this:
好吧,如果你用DisplayNameAttribute这样的方式装饰你的模型:
[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:
如果您想针对不同语言本地化您的应用程序,这一点更为重要,您可以使用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.
这也意味着您将拥有更多强类型视图。很容易对一个字符串进行胖手指,就像"FirstName"你必须输入很多一样,但是使用 helper 方法将允许编译器在大多数情况下捕捉到这样的错误。
回答by webnoob
LabelForallows you to control everything from your view model without worrying about the control.
LabelFor允许您控制视图模型中的所有内容,而无需担心控制。
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.
假设您在 2 个地方使用相同的视图模型,这意味着您可以在一个地方更改名称以更新所有控件。
Doesn't haveto be used, but it has its uses.
不会有被使用,但是它有它的用途。

