Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add a CSS class definition to the Html.LabelFor in MVC3?

I hope someone out there has some ideas. I would like to tidy up my code and so I already used the Html.LabelFor. However now I want to assign a CSS class to the labels.

Html.LabelFor(model => model.Customer.Description   ????)

Does anyone out there know if this is possible in MVC3. Note it's MVC3 I am using. Already I saw a post that talked about MVC2 and there being no simple solution.

like image 289
JudyJ Avatar asked May 07 '11 15:05

JudyJ


Video Answer


1 Answers

Here you go buddy-o:

namespace System.Web.Mvc.Html
{
  using System;
  using Collections.Generic;
  using Linq;
  using Linq.Expressions;
  using Mvc;

  public static class LabelExtensions
  {
    public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
    {
      return html.LabelFor(expression, null, htmlAttributes);
    }

    public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText, object htmlAttributes)
    {
      return html.LabelHelper(
            ModelMetadata.FromLambdaExpression(expression, html.ViewData),
            ExpressionHelper.GetExpressionText(expression),
            HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes),
            labelText);
    }

    private static MvcHtmlString LabelHelper(this HtmlHelper html, ModelMetadata metadata, string htmlFieldName, IDictionary<string, object> htmlAttributes, string labelText = null)
    {
      var str = labelText
            ?? (metadata.DisplayName
            ?? (metadata.PropertyName
            ?? htmlFieldName.Split(new[] { '.' }).Last()));

      if (string.IsNullOrEmpty(str))
        return MvcHtmlString.Empty;

      var tagBuilder = new TagBuilder("label");
      tagBuilder.MergeAttributes(htmlAttributes);
      tagBuilder.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
      tagBuilder.SetInnerText(str);

      return tagBuilder.ToMvcHtmlString(TagRenderMode.Normal);
    }

    private static MvcHtmlString ToMvcHtmlString(this TagBuilder tagBuilder, TagRenderMode renderMode)
    {
      return new MvcHtmlString(tagBuilder.ToString(renderMode));
    }
  }
}
like image 197
George R Avatar answered Oct 19 '22 19:10

George R