Val*_*mas 7 c# asp.net-mvc extension-methods
我正在进行扩展.
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));
}
Run Code Online (Sandbox Code Playgroud)
这一行:
if (htmlAttributes != null) builder.MergeAttributes(htmlAttributes);
Run Code Online (Sandbox Code Playgroud)
错误:
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.
Run Code Online (Sandbox Code Playgroud)
我试过了:
if (htmlAttributes != null) builder.MergeAttributes((Dictionary<string, string>)htmlAttributes);
Run Code Online (Sandbox Code Playgroud)
和
if (htmlAttributes != null) builder.MergeAttributes((Dictionary<string, object>)htmlAttributes);
Run Code Online (Sandbox Code Playgroud)
我怎样才能让它发挥作用?
Ale*_* K. 25
最好使用HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)而不是new,RouteValueDictionary(htmlAttributes)因为它支持用下划线拼写的数据短划线属性(例如data_click),并且没有直接依赖于RouteValueDictionary.
SLa*_*aks 13
您需要通过创建一个将匿名类型转换为字典RouteValueDictionary.
builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
Run Code Online (Sandbox Code Playgroud)
此构造函数将从对象的属性填充字典.