2011-06-06 208 views
15

可能重复:
Client Id for Property (ASP.Net MVC)如何指定ID为Html.LabelFor <>(MVC剃刀)

有没有一种方法,使刀片渲染ID属性的标签元素时使用Html.LabelFor <>助手?

例子:

.cshtml page 
@using (Html.BeginForm()) 
{ 
@Html.LabelFor(m => m.Foo) 
@Html.TextBoxFor(m => m.Foo) 
} 

呈现的页面

<form ...> 
<label for="Foo" id="Label_Foo" /> 
<input type="text" name="Foo" id="Foo" /> 
</form> 

仅供参考 - 我想要的ID添加到标签的唯一理由就是对CSS的设计。我更喜欢用ID来引用标签,而不是将标签包装在一个块(即div)中,然后对块进行造型。

+0

为什么你需要做的M => m.Foo为什么不m.Foo – Nikos 2012-04-17 14:45:13

+0

因为您必须插入一个可以读取而不是插入值的表达式。 – 2016-01-19 09:12:56

回答

26

不幸的是,这个帮助程序没有内置的重载,可以让您实现这一点。

幸运的,将采取几行代码来实现自己:

@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方法。

+0

很好的答案,谢谢你在这做这件事。 – camainc 2011-09-20 20:13:07

+1

在没有扩展名的最新版MVC中支持此方法。 – Todd 2013-11-17 22:09:53

1

和普通标签@Html.Label()

,你可以做到这一点,很容易一行代码...

public static HtmlString Label(this HtmlHelper helper, string target = "", string text = "", string id = "") 
{ 
    return new HtmlString(string.Format("<label id='{0}' for='{1}'>{2}</label>", id, target, text)); 
}