0

我知道 actionlink 使用路由表来显示 corrert 链接,但是 Html.Label 助手提供了什么优势?

4

3 回答 3

1

标签助手并没有做很多事情。它的功能是封装一小部分标记,这样你就不必每次都手动编写 HTML。它还提供智能感知。当您更改模型中的值时,这很有帮助,然后您不必返回并编辑您的视图。理想情况下,您的标签文本和目标应该由您的ViewModel使用驱动,LabelFor而不是在您的 HTML 中定义。

如果您查看Label帮助程序的源代码,它会执行以下操作:

//Create a new <label> element
TagBuilder tag = new TagBuilder("label");
//Add the attribute "for" with the id value of the target <input>
tag.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
//Set the label text <label>My Text</label>
tag.SetInnerText(resolvedLabelText);
//Merge any attributes specified in the htmlAttributes arguement (ex: class="style")
tag.MergeAttributes(htmlAttributes, replaceExisting: true);
//Write the output rendering, this is not a self closing tag </label>
return tag.ToMvcHtmlString(TagRenderMode.Normal);

注意:我在这里引用了 LabelFor 而不是 Label。但是,LabelFor 助手实际上在内部调用了 Label 助手。LabelFor 助手是最佳实践。

于 2013-01-28T19:37:17.773 回答
0

Html.Label并且Html.LabelForHTML 标签标签的包装器。此标记的核心“隐藏”功能之一是,如果它与输入控件关联,您可以通过单击标签将焦点设置到关联控件。这对于文本框和类似的东西来说没什么大不了的,但是将它与您的复选框和单选按钮一起使用将大大提高您的用户的可用性 - 单击标签与单击控件本身具有相同的效果。

于 2013-01-28T20:18:57.330 回答
0

只需从 mvc 书中阅读即可

“最后,值得注意的是,这些 HTML 帮助方法会自动对它们呈现的字段值进行 HTML 编码。这非常重要;否则,您的应用程序中将有无穷无尽的 XSS 漏洞。”

Pro ASP.NET MVC 2 框架

史蒂文·桑德森

于 2013-01-28T15:19:38.467 回答