views:

411

answers:

3

How would one add an "id" attribute to Html.LabelFor() in ASP.NET MVC2?

This is my label code:

<%=Html.LabelFor(x => x.FirstName)%>

This is my failed attempt:

<%=Html.LabelFor(x => x.FirstName, new { @id = "first-name" } )%>

Thanks.

A: 

The LabelFor, TextBoxFor, XXXFor methods automatically add the id based on the name of the property. I don't think you can override that. If you want to be able to set the id, you'll need to use the "non-For" methods like Html.TextBox.

Dave Swersky
Actually, I don't think that LabelFor adds an id at all -- the id would presumably be applied to the input field that is associated with the label. I think that you're right that you need to use the non-strongly-typed version to add HTML attributes, though.
tvanfosson
A: 

How about this extension method

public static class LabelExtensions

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

Edit

I think the better way would be to use the tagbuilder similar to this example and use the MergeAttribute function to include the id.

Ahmad
A: 

Here is an helper that should do what you need:

public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string id)
{
    ModelMetadata meta = ModelMetadata.FromLambdaExpression(expression, html.ViewData), 
    string ExpressionHelper.GetExpressionText(expression)

    string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
    if (String.IsNullOrEmpty(labelText)) {
        return MvcHtmlString.Empty;
    }

    TagBuilder tag = new TagBuilder("label");
    tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
    tag.MergeAttribute("id", is);
    tag.SetInnerText(labelText);
    return tag.ToMvcHtmlString(TagRenderMode.Normal);
}

a simple modification from the LabelFor helper in the asp.net mvc source.

moi_meme