为什么要使用LabelFor在MVC? [英] Why should I use LabelFor in MVC?

查看:273
本文介绍了为什么要使用LabelFor在MVC?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为什么要使用 LabelFor 而不是<标签>

Why should I use LabelFor instead of <label>?

如:

@Html.LabelFor(model => model.FirstName)
@Html.DisplayFor(model => model.FirstName)

VS

<label for="FirstName">First Name</label>
@Html.DisplayFor(model => model.FirstName)

接着上文,
@ p.s.w.g已覆盖了这一问题的DRY方面。我也想知道,如果它与定位有帮助。 IE浏览器。基于当前语言设置不同的标签。

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.

推荐答案

好吧,如果你装饰了你的车型的<一个href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.displaynameattribute.aspx\"><$c$c>DisplayNameAttribute像这样的:

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.

如果您希望您的本地化为不同的语言,您可以用<一个做应用​​这是更重要的href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute.aspx\"><$c$c>DisplayAttribute:

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.

这篇关于为什么要使用LabelFor在MVC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆