不幸的是,这个助手没有内置的重载可以让你实现这一点。
幸运的是,实现您自己的代码需要几行代码:
public static class LabelExtensions
{
public static MvcHtmlString LabelFor<TModel, TValue>(
this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression,
object htmlAttributes
)
{
return LabelHelper(
html,
ModelMetadata.FromLambdaExpression(expression, html.ViewData),
ExpressionHelper.GetExpressionText(expression),
htmlAttributes
);
}
private static MvcHtmlString LabelHelper(
HtmlHelper html,
ModelMetadata metadata,
string htmlFieldName,
object htmlAttributes
)
{
string resolvedLabelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
if (string.IsNullOrEmpty(resolvedLabelText))
{
return MvcHtmlString.Empty;
}
TagBuilder tag = new TagBuilder("label");
tag.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
tag.MergeAttributes(new RouteValueDictionary(htmlAttributes));
tag.SetInnerText(resolvedLabelText);
return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
}
}
一旦纳入范围,请在您的视图中使用此帮助器:
@Html.LabelFor(m => m.Foo, new { id = "Foo" })
@Html.TextBoxFor(m => m.Foo)
备注:因为现在由您来管理 HTML id,请确保它们在整个文档中是唯一的。
备注2:我无耻抄袭修改了ASP.NET MVC 3源码中的LabelHelper方法。