2010-09-06 11 views
5

¿Cómo creo un ASP.Net MVC Helper para un Html.Label que toma atributos?ASP.Net MVC Html.Label con la lista de atributos?

Actualmente, cuando defino un Html.TextBox, puedo pasar una lista de atributos. Más o menos como se detalla a continuación:

new {disabled="disabled", @class="pcTextBoxWithoutPaddingDisabled"})%> 

Sin embargo, no parece que la etiqueta Html.Label tenga esta función. Como resultado, tengo que definir mis etiquetas usando la etiqueta. Más o menos como se detalla a continuación:

<label class="pcLabelBlackWithoutPadding"> 

Me gustaría ser consistente en cómo se crea mi elemento Html.

Entonces, ¿cómo creo un Html.Label que incluirá una lista de atributos?

Gracias por su ayuda.

Respuesta

2

Sugeriría crear su propio método de extensión HtmlHelper y usar un TagBuilder para crear la etiqueta.

public static HtmlHelperExtensions 
{ 
     public static Label(this HtmlHelper helper, string labelText, object properties) 
     { 
      var builder = new TagBuilder("label"); 
      builder.MergeAttributes(new RouteValueDictionary(properties)); 
      builder.SetInnerText(labelText); 
      return builder.ToString(TagRenderMode.Normal); 
     } 
} 

Véase la MVC source code para obtener ideas sobre cómo crear un ayudante etiqueta inflexible de tipos. Tenga en cuenta que deberá agregar el espacio de nombres que contiene sus extensiones a la página o web.config para poder usarlo.

9

Esta versión se actualiza para MVC3:

public static MvcHtmlString Label(this HtmlHelper helper, String htmlFieldName, String labelText, Object htmlAttributes) 
{ 
    ModelMetadata metadata = ModelMetadata.FromStringExpression(htmlFieldName, helper.ViewData); 

    String innerText = labelText ?? (metadata.DisplayName ?? (metadata.PropertyName ?? htmlFieldName.Split('.').Last())); 

    if (String.IsNullOrEmpty(innerText)) 
    { 
     return MvcHtmlString.Empty; 
    } 

    TagBuilder tagBuilder = new TagBuilder("label"); 
    tagBuilder.Attributes.Add("for", TagBuilder.CreateSanitizedId(helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName))); 
    tagBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributes)); 
    tagBuilder.SetInnerText(innerText); 

    return new MvcHtmlString(tagBuilder.ToString(TagRenderMode.Normal)); 

} 
+0

realmente funciona :) –

3

he modificado el código Alexandr un poco con la expresión lambda, por si alguien necesitaba la expresión lambda.

uso:

@Html.LabelFor(model => model.Property , new { @class = "bigFont" }) 

código:

public static MvcHtmlString LabelFor<TModel, TProperty>(
     this HtmlHelper<TModel> htmlHelper, 
     Expression<Func<TModel, TProperty>> expression, Object htmlAttributes) 
    { 
     var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); 

     var innerText = metadata.DisplayName ?? metadata.PropertyName; 

     if (String.IsNullOrEmpty(innerText)) 
     { 
      return MvcHtmlString.Empty; 
     } 

     var tagBuilder = new TagBuilder("label"); 
     tagBuilder.Attributes.Add("for", TagBuilder.CreateSanitizedId(htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(metadata.PropertyName))); 
     tagBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributes)); 
     tagBuilder.SetInnerText(innerText); 

     return new MvcHtmlString(tagBuilder.ToString(TagRenderMode.Normal)); 
    } 
+0

solución perfecta. – dotTutorials

Cuestiones relacionadas