Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 349
Valamas Avatar asked Jul 26 '11 01:07

Valamas


1 Answers

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.

like image 151
Alexander K. Avatar answered Sep 23 '22 16:09

Alexander K.