Valamas
Valamas

Reputation: 24729

htmlAttributes not merging with tag builder in my extension

I am making an extension.

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

This line:

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

Errors with:

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.

I have tried:

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

and

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

How can I get this to work?

Upvotes: 7

Views: 3311

Answers (2)

Alexander K.
Alexander K.

Reputation: 1222

It's better to use HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes) instead of new RouteValueDictionary(htmlAttributes) because it supports data dash attributes spelled with underscore (e.g. data_click) and there is no direct dependency on RouteValueDictionary.

Upvotes: 25

SLaks
SLaks

Reputation: 887451

You need to convert the anonymous type to a dictionary by creating a RouteValueDictionary.

builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));

This constructor will populate the dictionary from the properties of the object.

Upvotes: 13

Related Questions