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

后端 未结 2 1674
孤城傲影
孤城傲影 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:47

    There is no built in way to do this in MVC 3. You will have to write your helper that does this. Take a look at the LabelExtensions class to see how it is done.

    0 讨论(0)
  • 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<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));
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题