mvc Label helper有什么意义?

时间:2013-01-28 15:11:48

标签: asp.net-mvc html-helper

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

3 个答案:

答案 0 :(得分:1)

标签助手并没有做很多事情。它的功能是封装一小部分标记,这样您就不必每次都手动编写HTML。它还提供 intellisense 。当您更改模型中的值时,这非常有用,您无需返回并编辑视图。理想情况下,您的标签文字和定位应使用ViewModelLabelFor开始,而不是在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帮助程序是最佳实践。

答案 1 :(得分:0)

请从mvc书中读到这个

“最后,值得注意的是,这些HTML帮助程序方法会自动对字段值进行HTML编码 他们渲染。这非常重要;否则,你将无法结束XSS漏洞 在整个申请过程中。“

临 ASP.NET MVC 2 框架

史蒂文桑德森

答案 2 :(得分:0)

Html.LabelHtml.LabelForHTML label标记周围的包装器。此标记的核心“隐藏”功能之一是,如果它与输入控件关联,则可以通过单击标签将焦点设置为关联的控件。对于文本框和类似的东西来说,这不是什么大问题,但是将它与复选框和单选按钮一起使用对于用户来说将是一个显着的可用性提升 - 单击标签与在控件本身内单击具有相同的效果。