2011-07-26 9 views
7

Robię rozszerzenie.htmlAtagi nie łączą się z konstruktorem tagów w moim rozszerzeniu

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

tej linii:

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

Błędy z:

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. 

próbowałem:

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

i

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

Jak mogę to uruchomić?

Odpowiedz

13

Konwertuj typ anonimowy na słownik, tworząc numer RouteValueDictionary.

builder.MergeAttributes(new RouteValueDictionary(htmlAttributes)); 

Ten konstruktor zapełni słownik z właściwości obiektu.

25

Lepiej używać HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes) zamiast nowego RouteValueDictionary(htmlAttributes), ponieważ obsługuje on atrybuty kreskowania danych napisane za pomocą podkreślenia (np. Data_click) i nie istnieje bezpośrednia zależność od parametru RouteValueDictionary.

+1

to było dla mnie bardzo pomocne - rozglądałem się za czymś takim. –

Powiązane problemy