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)
{
开发者_Python百科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?
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.
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.
精彩评论