我正在进行扩展。
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);
我怎样才能让它发挥作用?
答案 0 :(得分:25)
最好使用HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)
而不是新的RouteValueDictionary(htmlAttributes)
,因为它支持使用下划线拼写的数据短划线属性(例如data_click),并且没有直接依赖于RouteValueDictionary。
答案 1 :(得分:13)
您需要通过创建RouteValueDictionary
来将匿名类型转换为字典。
builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
此构造函数将从对象的属性填充字典。