Asp.net-Mvc-3

擴展 MVC3 razor Html.LabelFor 以添加 css 類

  • April 29, 2016

我正在嘗試在 EditorTemplate 上向 Html.LabelFor 添加一個 CSS 類

@Html.LabelFor(model => model.Name, new { @class = "myLabel" })

例如,我的期望:label 應該選擇 css 類。

為此,我嘗試使用以下程式碼擴展標籤,但我的標籤未顯示。我在這裡做錯了什麼?

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));
       }
   }

例如,如果我沒有指定 css 類 @Html.LabelFor(model => model.Name) ,那麼它會顯示標籤。但我無法將 css 應用於我的標籤。我想在頁面載入時以藍色顯示標籤。然後使用 jquey 根據使用者操作更改標籤樣式。一切都很好,在我的頁面上,除了我無法擴展和添加 css 類到我的標籤。

我懷疑您忘記將定義此 LabelExtensions 類的名稱空間帶入視圖的範圍內。例如,如果這個類是在MyProject.Extensions命名空間內定義的:

namespace MyProject.Extensions
{
   public static class LabelExtensions
   {
       ...
   }
}

確保您已將此命名空間納入範圍:

@using MyProject.Extensions
@model MyViewModel
...
@Html.LabelFor(model => model.Name, new { @class = "myLabel" })

您正在使用 html.LabelHelper

但是您已經定義了自己的 LabelHelper 方法,所以使用它 =)

引用自:https://stackoverflow.com/questions/10603016