我可以在MVC3中的Html.LabelFor中添加CSS类定义吗?

Jud*_*dyJ 13 asp.net-mvc asp.net-mvc-3

我希望那里有人有一些想法.我想整理我的代码,所以我已经使用了Html.LabelFor.但是现在我想为标签分配一个CSS类.

Html.LabelFor(model => model.Customer.Description   ????)
Run Code Online (Sandbox Code Playgroud)

有没有人知道这是否可能在MVC3中.注意它是我正在使用的MVC3.我已经看到一篇关于MVC2的帖子,并没有简单的解决方案.

Geo*_*e R 15

哥们儿来这里:

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));
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


mar*_*ind 9

在MVC 3中没有内置的方法来执行此操作.您必须编写执行此操作的帮助程序.看看LabelExtensions课程,看看它是如何完成的.

  • @LeeGarner好吧,我是MVC团队的成员,我不确定为什么Label帮助器没有采用`htmlAttributes`参数.也许是一些疏忽.我将提交一个错误,以确保我们在下一个版本中添加它. (5认同)
  • @George R - 下一版本的MVC将支持一个`htmlAttributes`参数,就像启用此场景的所有其他助手一样.我们可能不会公开`LabelHelper`函数.但我希望这能满足您的需求. (4认同)