No veo ninguna forma de obtener una declaración de tipo anónimo para aceptar data-myid
, ya que ese no es un nombre de propiedad válido en C#. Una opción sería la creación de una nueva sobrecarga que toma un parámetro extra dataAttributes
, y antepone a los nombres data-
para usted ...
using System.ComponentModel;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
static class TextBoxExtensions
{
public static string TextBox(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes, object dataAttributes)
{
RouteValueDictionary attributes = new RouteValueDictionary(htmlAttributes);
attributes.AddDataAttributes(dataAttributes);
return htmlHelper.TextBox(
name,
value,
((IDictionary<string, object>)attributes);
}
private static void AddDataAttributes(this RouteValueDictionary dictionary, object values)
{
if (values != null)
{
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(values))
{
object obj2 = descriptor.GetValue(values);
dictionary.Add("data-" + descriptor.Name, obj2);
}
}
}
}
A continuación, se puede añadir un atributo data-myid
con
<%= Html.TextBox ("textBox", "Value",
new { title = "Some ordinary attribute" },
new { myid = m.ID }) %>
Sin embargo , eso te deja para crear esa sobrecarga en cualquier otro método que quieras para aceptar atributos de datos, lo cual es un problema. Usted podría conseguir alrededor de ese moviendo la lógica a un
public static IDictionary<string,object> MergeDataAttributes(
this HtmlHelper htmlHelper,
object htmlAttributes,
object dataAttributes)
y llamarlo como
<%= Html.TextBox ("textBox", "Value",
Html.MergeDataAttributes(new { title = "Some ordinary attribute" }, new { myid = m.ID })) %>
Ver esta pregunta 'html con guión atributos con asp.net mvc' http://stackoverflow.com/questions/2897733/hyphenated-html-attributes-with-asp-net-mvc/12091886#12091886 –
nota: la más reciente la respuesta correcta es http: // stackoverflow.com/a/5872576/1037948, más abajo en esta página si no te gusta desplazarte;) – drzaus