C# html助手使用字典<;字符串,对象>;,如何使用此参数?
如果html助手将idictionary作为参数,如何使用它 我试过:C# html助手使用字典<;字符串,对象>;,如何使用此参数?,c#,asp.net,asp.net-mvc,html-helper,C#,Asp.net,Asp.net Mvc,Html Helper,如果html助手将idictionary作为参数,如何使用它 我试过: <%= Html.Blah( new { id = "blah" }) %> 但这是行不通的。如果您不想使用通用字典,哈希表也实现了IDictionary <%= Html.Blah( new Dictionary<string, object>(){ { "key", "value" }
<%= Html.Blah( new { id = "blah" }) %>
但这是行不通的。
如果您不想使用通用字典,哈希表也实现了IDictionary
<%= Html.Blah( new Dictionary<string, object>(){
{ "key", "value" },
{ "key1", someObj },
{ "blah", 1 }
} );
Html.Blah(new Hashtable(){
{"id", "blah"}
});
内置的HtmlHelper扩展方法通常提供重载,这些重载采用对象
参数而不是IDictionary
,以便在尝试时使用匿名类型调用它们
如果这是您自己的方法,您可以创建另一个类似以下内容的扩展方法:
public static string Blah(this HtmlHelper html, object htmlAttributes)
{
return html.Blah(new RouteValueDictionary(htmlAttributes));
}
html.Blah(new RouteValueDictionary(new { id = "blah" }));
RouteValueDictionary的构造函数接受一个对象,并使用传入对象的公共属性填充自身。我相信这也是内置的HtmlHelper扩展方法的典型功能
或者,您可以这样调用该方法:
public static string Blah(this HtmlHelper html, object htmlAttributes)
{
return html.Blah(new RouteValueDictionary(htmlAttributes));
}
html.Blah(new RouteValueDictionary(new { id = "blah" }));
我还没有看过,但是很明显RouteValueDictionary类正在进行一些反射,以便能够识别对象的属性。请注意,以防这是您关心的问题。以防其他人也遇到这个问题。存在将匿名对象转换为字典的帮助器方法
例如:
HtmlHelper.AnonymousObjectToHtmlAttributes( new { ng_model = "vm" } );
换句话说,您可以根据OP的问题创建HTML帮助器方法来获取对象并在内部使用此帮助器方法。例如
public static string Blah(this HtmlHelper html, object htmlAttributes)
{
// Create a dictionary from the object
HtmlHelper.AnonymousObjectToHtmlAttributes( htmlAttributes );
// ... rest of implementation
}