不幸的是,这个帮助程序没有内置的重载,可以让您实现这一点。
幸运的,将采取几行代码来实现自己:
@Html.LabelFor(m => m.Foo, new { id = "Foo" })
@Html.TextBoxFor(m => m.Foo)
备注:
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 ID,确保它们在整个文档中都是唯一的。
备注2:我无耻地抄袭并修改了ASP.NET MVC 3源代码中的LabelHelper
方法。
为什么你需要做的M => m.Foo为什么不m.Foo – Nikos 2012-04-17 14:45:13
因为您必须插入一个可以读取而不是插入值的表达式。 – 2016-01-19 09:12:56