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

后端 未结 2 1688
孤城傲影
孤城傲影 2020-12-28 19:29

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.

2条回答
  •  温柔的废话
    2020-12-28 19:52

    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(this HtmlHelper html, Expression> expression, object htmlAttributes)
        {
          return html.LabelFor(expression, null, htmlAttributes);
        }
    
        public static MvcHtmlString LabelFor(this HtmlHelper html, Expression> 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 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));
        }
      }
    }
    

提交回复
热议问题