2011-07-26 5 views
7

Estoy haciendo una extensión.htmlAttributes que no se combinan con el generador de etiquetas en mi extensión

public static MvcHtmlString Image(this HtmlHelper helper, string src, object htmlAttributes = null) 
{ 
    TagBuilder builder = new TagBuilder("img"); 
    builder.MergeAttribute("src", src); 
    if (htmlAttributes != null) builder.MergeAttributes(htmlAttributes); 
    return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing)); 
} 

esta línea:

if (htmlAttributes != null) builder.MergeAttributes(htmlAttributes); 

errores con:

The type arguments for method 'System.Web.Mvc.TagBuilder.MergeAttributes<TKey,TValue>(System.Collections.Generic.IDictionary<TKey,TValue>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. 

que he intentado:

if (htmlAttributes != null) builder.MergeAttributes((Dictionary<string, string>)htmlAttributes); 

y

if (htmlAttributes != null) builder.MergeAttributes((Dictionary<string, object>)htmlAttributes); 

¿Cómo puedo hacer que funcione?

Respuesta

13

Necesita convertir el tipo anónimo a un diccionario creando RouteValueDictionary.

builder.MergeAttributes(new RouteValueDictionary(htmlAttributes)); 

Este constructor se rellenará el diccionario de las propiedades del objeto.

25

Es mejor usar HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes) en lugar de RouteValueDictionary(htmlAttributes) nuevo porque admite atributos de dash de datos deletreados con guión bajo (por ejemplo, data_click) y no hay dependencia directa en RouteValueDictionary.

+1

esto fue realmente útil para mí, busqué algo así como esto. –

Cuestiones relacionadas