gpt4 book ai didi

asp.net-mvc - HtmlHelper 方法和 RouteValueDictionary

转载 作者:行者123 更新时间:2023-12-02 10:29:45 25 4
gpt4 key购买 nike

在编写 htmlhelper 扩展时,如果我想为我的 htmlhelper 扩展方法支持类似结构的构造函数,我使用 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 ...我知道你不能只转换 htmlAttributesIDictionary<string, object> ...虽然我不确定为什么,这可能是我感到困惑的地方。不应该RouteValueDictionary与路由有关,因此与 HtmlHelper 方法无关?就像我说的,我可能错过了重点,所以如果有人能告诉我我错过了什么,我会很高兴。

干杯...

编辑:回应 Dan 的回答 -->

我只是按照我在 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))
}

显然是一个捷径,但这是一种 SCSS 还是可以这样做?

最佳答案

我强烈建议您查看 Rob Conery 的 blog post关于这样的事情。

它的主要内容是:

代码转储:

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"

希望这是有道理的。

关于asp.net-mvc - HtmlHelper 方法和 RouteValueDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/683952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com