.NET MVC - How to assign a class to Html.LabelFor?

Sadly, in MVC 3 the Html.LabelFor() method has no method signatures that permit a direct class declaration. However, MVC 4 adds 2 overloads that accept an htmlAttributes anonymous object.

As with all HtmlHelpers it's important to remember that the C# compiler sees class as reserved word.

So if you use the @ before the class attribute it works around the problem, ie:

@Html.LabelFor(model => model.PhysicalPostcode, new { @class= "SmallInput" })

The @ symbol makes the "class" a literal that is passed through.


Overload of LabelFor:

public static class NewLabelExtensions
{
    public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
    {
        return LabelFor(html, expression, new RouteValueDictionary(htmlAttributes));
    }
    public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
        string htmlFieldName = 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.MergeAttributes(htmlAttributes);
        tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
        tag.SetInnerText(labelText);
        return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
    }
}

http://weblogs.asp.net/imranbaloch/archive/2010/07/03/asp-net-mvc-labelfor-helper-with-htmlattributes.aspx


Okay, looking at the source (System.Web.Mvc.Html.LabelExtensions.cs) for this method, there doesn't seem to be a way to do this with an HtmlHelper in ASP.NET MVC 2. I think your best bet is to either create your own HtmlHelper or do the following for this specific label:

<label for="Name" class="myLabel"><%= Model.Name %></label>