如何为Html.LabelFor <>(MVC Razor)指定ID

Jed*_*Jed 18 html-helper razor asp.net-mvc-3

可能重复:
属性的客户端ID(ASP.Net MVC)

有没有办法让Razor在使用Html.LabelFor <>帮助器时为Label元素呈现ID属性?

例:

.cshtml page
@using (Html.BeginForm())
{
@Html.LabelFor(m => m.Foo)
@Html.TextBoxFor(m => m.Foo)
}
Run Code Online (Sandbox Code Playgroud)

呈现页面

<form ...>
<label for="Foo" id="Label_Foo" />
<input type="text" name="Foo" id="Foo" />
</form>
Run Code Online (Sandbox Code Playgroud)

仅供参考 - 我想在标签上添加ID的唯一原因是CSS设计.我更喜欢用ID引用Label而不是将Label包装在一个块(即div)中,然后设置块的样式.

Dar*_*rov 28

不幸的是,这个助手没有内置的重载,可以让你实现这一点.

幸运的是,需要几行代码才能实现自己的代码:

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

并且一旦进入范围,请在视图中使用此帮助程序:

@Html.LabelFor(m => m.Foo, new { id = "Foo" })
@Html.TextBoxFor(m => m.Foo)
Run Code Online (Sandbox Code Playgroud)

备注:因为现在由您来管理HTML ID,确保它们在整个文档中是唯一的.

备注2:我无耻地剽窃并修改LabelHelper了ASP.NET MVC 3源代码中的方法.