How to specify ID for an Html.LabelFor (MVC Razor) [duplicate]

Unfortunately there is no built-in overload of this helper that allows you to achieve this.

Fortunately it would take a couple of lines of code to implement your own:

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));
    }
}

and once brought into scope use this helper in your view:

@Html.LabelFor(m => m.Foo, new { id = "Foo" })
@Html.TextBoxFor(m => m.Foo)

Remark: because now it is up to you to manage HTML ids, make sure that they are unique throughout the entire document.

Remark2: I have shamelessly plagiarized and modified the LabelHelper method from the ASP.NET MVC 3 source code.

Leave a Comment