2012-03-27 7 views
11

Html.Label e Html.LabelFor non supportano il parametro htmlAttributes come fa la maggior parte degli altri helper. Vorrei impostare il class tuttavia. Qualcosa di simile a questo:Come estendere gli helper MVC3 Label e LabelFor HTML? I metodi di supporto

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

Esiste un facile modo di estendere Label/LabelFor senza ricorrere alla copia ed estendendo l'uscita DISASM ILSpy di questi metodi?

risposta

25

si può facilmente estendere l'etichetta creando il proprio LabelFor:

Qualcosa di simile dovrebbe fare ciò che è necessario

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) 
{ 
    ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData); 
    string htmlFieldName = ExpressionHelper.GetExpressionText(expression); 
    string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last(); 
    if (String.IsNullOrEmpty(labelText)) 
    { 
    return MvcHtmlString.Empty; 
    } 

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

Aggiornamento Per utilizzare il metodo di estensione appena creato nel progetto, aggiungere questa riga nel vostro Views\web.config

<pages> 
    <namespaces> 
    <add namespace="System.Web.Helpers" /> 
    <add namespace="System.Web.Mvc" /> 
    <add namespace="System.Web.Mvc.Ajax" /> 
    <add namespace="System.Web.Mvc.Html" /> 
    <add namespace="System.Web.Routing" /> 
    <add namespace="System.Web.WebPages" /> 
    <add namespace="MyProject.Helpers" /> <-- my extension 

    ... 

</namespaces> 
</pages> 
+0

lo so, ma io sto cercando di evitare replicare il smontato/uscita della sorgente originale. Il codice originale consiste di 22 metodi, farlo correttamente dovrei scavalcarli tutti. – batkuip

+2

no. devi semplicemente creare il tuo progetto di estensione e inserire nel tuo web.config la chiamata al tuo progetto. – Iridio

6
public static class LabelExtensions 
{ 
    public static IHtmlString LabelFor<TModel, TProperty>(
     this HtmlHelper<TModel> htmlHelper, 
     Expression<Func<TModel, TProperty>> expression, 
     string labelText, 
     object htmlAttributes 
    ) 
    { 
     var metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData); 
     var htmlFieldName = ExpressionHelper.GetExpressionText(expression); 
     return LabelHelper(htmlHelper, metadata, htmlFieldName, labelText, htmlAttributes); 
    } 

    public static IHtmlString Label(this HtmlHelper htmlHelper, string expression, string labelText, object htmlAttributes) 
    { 
     var metadata = ModelMetadata.FromStringExpression(expression, htmlHelper.ViewData); 
     return LabelHelper(htmlHelper, metadata, expression, labelText, htmlAttributes); 
    } 

    private static IHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string labelText, object htmlAttributes) 
    { 
     string str = labelText ?? (metadata.DisplayName ?? (metadata.PropertyName ?? htmlFieldName.Split(new char[] { '.' }).Last<string>())); 
     if (string.IsNullOrEmpty(str)) 
     { 
      return MvcHtmlString.Empty; 
     } 
     TagBuilder tagBuilder = new TagBuilder("label"); 
     tagBuilder.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName))); 
     var attributes = new RouteValueDictionary(htmlAttributes); 
     tagBuilder.MergeAttributes(attributes); 
     tagBuilder.SetInnerText(str); 
     return new HtmlString(tagBuilder.ToString(TagRenderMode.Normal)); 
    } 
} 

e poi:

@Html.LabelFor(x => x.SomeProperty, null, new { @class = "foo" }) 

o:

@Html.Label("SomeProperty", null, new { @class = "foo" }) 
+0

Scusa amico se non mi fossi chiarito. L'ho fatto (copiando la fonte MVC ed estendendolo), tuttavia è qualcosa che vorrei evitare per una serie di motivi. Inoltre mi piace mantenere le cose ASCIUTTE. Speravo che ci sarebbe stato qualcosa di più elegante. – batkuip

+1

Spiacente, non c'è niente là fuori che ti permetta di fare questo. L'helper integrato non è estensibile e ha gli attributi hardcoded. –

+0

Come posso far sì che il compilatore non si misuri tra myProject.Helpers.LabelExtensions.LabelFor e 'System.Web.Mvc.Html.LabelExtensions.LabelFor (necessario per altre cose nella pagina)? – Ungaro