2011-08-02 102 views
0

我開始使用這個擴展,我在網上找到:我怎樣才能改變我的擴展方法在C#

public static class NewLabelExtensions 
    { 
     public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes) 
     { 
      return LabelFor(html, expression, new RouteValueDictionary(htmlAttributes)); 
     } 
     public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes) 
     { 
      var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData); 
      var htmlFieldName = ExpressionHelper.GetExpressionText(expression); 
      var labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last(); 
      if (String.IsNullOrEmpty(labelText)) 
      { 
       return MvcHtmlString.Empty; 
      } 

      var tag = new TagBuilder("label"); 
      tag.MergeAttributes(htmlAttributes); 
      tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName)); 
      tag.SetInnerText(labelText); 
      return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal)); 
     } 
    } 

我用這樣的:

@Html.LabelFor(m => m.Login.RememberMe, new { @class = "adm" }) 

的結果是這樣的:

<label class="adm" for="Login_RememberMe">Remember me?</label> 

但是我想要這個標籤的樣式。我不太瞭解我正在使用的代碼。任何人都可以建議更改上面的代碼,使LabelFor方法生成?

<label class="adm" id="Login_RememberMe" for="Login_RememberMe">Remember me?</label> 

感謝

+0

爲什麼要創建一個標籤本身? ID和屬性不應該是相同的。 – VJAI

回答

2

你只需要添加下面一行:

tag.Attributes.Add("id", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName)); 

代碼:

public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes) 
    { 
     var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData); 
     var htmlFieldName = ExpressionHelper.GetExpressionText(expression); 
     var labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last(); 
     if (String.IsNullOrEmpty(labelText)) 
     { 
      return MvcHtmlString.Empty; 
     } 

     var tag = new TagBuilder("label"); 
     tag.MergeAttributes(htmlAttributes); 
     tag.Attributes.Add("id", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName)); 
     tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName)); 
     tag.SetInnerText(labelText); 
     return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal)); 
    }