métodos HtmlHelper e RouteValueDictionary
-
22-08-2019 - |
Pergunta
Quando escrever uma extensão HtmlHelper se eu quiser apoiar os ctors estrutura semelhante para o meu método de extensão HtmlHelper, eu uso RouteValueDictionary
da seguinte forma:
public static string ListBoxDict(this HtmlHelper htmlHelper,
string name,
object value,
object htmlAttributes)
{
return ListBoxDict(htmlHelper,
name,
value,
((IDictionary<string, object>)
new RouteValueDictionary(htmlAttributes)));
}
A minha pergunta realmente é por isso a necessidade de RouteValueDictionary
... Eu sei que você não pode simplesmente lançar a htmlAttributes
para IDictionary<string, object>
... embora eu não sei por que e que pode ser onde eu estou confuso. não deve ser RouteValueDictionary
a ver com roteamento e, portanto, nada a ver com HtmlHelper métodos? Como eu disse, eu provavelmente estou perdendo o ponto, então eu ficaria feliz se alguém poderia me dizer o que eu perdi.
Felicidades ...
edit: em resposta a resposta de Dan ->
Eu estava apenas seguindo o que eu tinha visto em uso no código fonte MVC para ajudantes de entrada ...
- ver "
src\SystemWebMvc\Mvc\Html\InputExtensions.cs
"
Ele faz o seguinte:
public static string TextBox(this HtmlHelper htmlHelper,
string name,
object value,
object htmlAttributes)
{
return TextBox(htmlHelper,
name,
value,
new RouteValueDictionary(htmlAttributes))
}
Claramente um atalho, mas é um abastardamento ou é ok para fazê-lo?
Solução
Eu fortemente recomendo olhar de Rob Conery post sobre algo como isto.
A carne e vegetais do que é esta:
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;
}
Uso:
public static string ListBoxDict(this HtmlHelper htmlHelper,
string name,
object value,
object htmlAttributes)
{
return htmlHelper.ListBoxDict(name,
value,
htmlAttributes.ToAttributeList()));
}
O que .ToAttributeList()
faz é converter o seu objeto htmlAttribute para
name = "valor"
Espero que isso faz sentido.