htmlAttributes не сливается с компоновщиком тегов в моем расширении - PullRequest
7 голосов
/ 26 июля 2011

Я делаю расширение.

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

Эта строка:

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

Ошибки с:

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.

Я пробовал:

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

и

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

Как мне заставить это работать?

Ответы [ 2 ]

25 голосов
/ 21 декабря 2012

Лучше использовать HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes) вместо нового RouteValueDictionary(htmlAttributes), поскольку он поддерживает атрибуты тире данных, записанные с подчеркиванием (например, data_click), и прямой зависимости от RouteValueDictionary нет.

13 голосов
/ 26 июля 2011

Необходимо преобразовать анонимный тип в словарь, создав RouteValueDictionary.

builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));

Этот конструктор будет заполнять словарь из свойств объекта.

...