HtmlHelper メソッドと RouteValueDictionary
-
22-08-2019 - |
質問
htmlhelper 拡張機能を作成するときに、htmlhelper 拡張メソッドで同様の構造の ctor をサポートしたい場合は、次のようにします。 RouteValueDictionary
次のように:
public static string ListBoxDict(this HtmlHelper htmlHelper,
string name,
object value,
object htmlAttributes)
{
return ListBoxDict(htmlHelper,
name,
value,
((IDictionary<string, object>)
new RouteValueDictionary(htmlAttributes)));
}
私の質問は、なぜ必要なのかということです。 RouteValueDictionary
...ただキャストできないことはわかっています htmlAttributes
に IDictionary<string, object>
...理由はわかりませんが、それが私が混乱しているところかもしれません。すべきではありません 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 の記事を参照することを強くお勧めします。 ブログ投稿 このようなことについて。
その肉と野菜はこんな感じです。
コードダンプ:
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 オブジェクトを次のように変換します。
名前 = "値"
これが理にかなっていることを願っています。
所属していません StackOverflow