在编写htmlhelper扩展时如果我想为我的htmlhelper扩展方法支持类似结构的ctors,我使用RouteValueDictionary
如下:
public static string ListBoxDict(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes) { return ListBoxDict(htmlHelper, name, value, ((IDictionary) new RouteValueDictionary(htmlAttributes))); }
我的问题真的是为什么需要RouteValueDictionary
......我知道你不能只是投了htmlAttributes
到IDictionary
......虽然我不知道为什么,并且可能是在那里我很困惑.不RouteValueDictionary
应该与路由有关,因此与HtmlHelper方法无关?就像我说的那样,我可能会忽略这一点,所以如果有人能告诉我我错过了什么,我会很高兴.
干杯...
编辑:回应丹的回答 - >
我只是按照我在mvc源代码中看到的用于输入助手的内容...
看" src\SystemWebMvc\Mvc\Html\InputExtensions.cs
"
它做如下:
public static string TextBox(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes) { return TextBox(htmlHelper, name, value, new RouteValueDictionary(htmlAttributes)) }
显然是捷径,但它是一个混蛋还是可以做到的?
我强烈建议您查看Rob Conery的博客文章.
它的肉和蔬菜是这样的:
Codedump:
public static string ToAttributeList(this object list) { StringBuilder sb = new StringBuilder(); if (list != null) { Hashtable attributeHash = GetPropertyHash(list); string resultFormat = "{0}=\"{1}\" "; foreach (string attribute in attributeHash.Keys) { sb.AppendFormat(resultFormat, attribute.Replace("_", ""), attributeHash[attribute]); } } return sb.ToString(); } public static string ToAttributeList(this object list, params object[] ignoreList) { Hashtable attributeHash = GetPropertyHash(list); string resultFormat = "{0}=\"{1}\" "; StringBuilder sb = new StringBuilder(); foreach (string attribute in attributeHash.Keys) { if (!ignoreList.Contains(attribute)) { sb.AppendFormat(resultFormat, attribute, attributeHash[attribute]); } } return sb.ToString(); } public static Hashtable GetPropertyHash(object properties) { Hashtable values = null; if (properties != null) { values = new Hashtable(); PropertyDescriptorCollection props = TypeDescriptor.GetProperties(properties); foreach (PropertyDescriptor prop in props) { values.Add(prop.Name, prop.GetValue(properties)); } } return values; }
用法:
public static string ListBoxDict(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes) { return htmlHelper.ListBoxDict(name, value, htmlAttributes.ToAttributeList())); }
什么.ToAttributeList()
是将htmlAttribute对象转换为
name ="value"
希望这是有道理的.