2012-05-15 8 views
14

を追加するHtml.LabelFor MVC3かみそりを拡張します。は、私はEditorTemplate</p> <pre><code>@Html.LabelFor(model => model.Name, new { @class = "myLabel" }) </code></pre> <p>例えば私の期待にHtml.LabelForするCSSクラスを追加しようとしていますcssクラス

このため、次のコードでLabelを拡張しようとしましたが、ラベルが表示されません。 ここで何が間違っていますか?

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

私は例@Html.LabelFor(model => model.Name)のCSSクラスを指定しておりません場合は、それはラベルを示します。 しかし私は自分のラベルにCSSを適用できません。 ページが読み込まれたときに青色でラベルを表示したい場合、jquey.Allを使用してユーザーの操作に基づいてラベルスタイルを変更するには、ページを拡張してCSSを追加できない私のラベルにクラス。

+1

"not working"を定義してください。あなたが期待している結果は何ですか?また、あなたが受け取った結果は何ですか? – Aaronaught

+0

あなたはどんな問題を抱えていますか? –

答えて

16

このLabelExtensionsクラスを定義した名前空間をビューのスコープ内に持って来るのを忘れたと思います。このクラスはMyProject.Extensions名前空間内で定義されているのであれば、たとえば:

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

は、あなたがスコープにこの名前空間を持ってきたことを確認してください。

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

あなたは

をhtml.LabelHelper使用していますしかし、あなた自身のLabelHelperメソッドを定義していますので、それを使用してください)=

関連する問題

 関連する問題