Non riesco a vedere alcun modo per ottenere una dichiarazione di tipo anonima per accettare data-myid
, poiché non è un nome di proprietà valido in C#. Una possibilità potrebbe essere quella di creare un nuovo overload che accetta un parametro supplementare dataAttributes
, e antepone data-
ai nomi per voi ...
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);
}
}
}
}
Quindi è possibile aggiungere un attributo data-myid
con
<%= Html.TextBox ("textBox", "Value",
new { title = "Some ordinary attribute" },
new { myid = m.ID }) %>
Tuttavia , che ti lascia creare questo sovraccarico su qualsiasi altro metodo che vuoi accettare attributi di dati, il che è un dolore. Si potrebbe ottenere in giro che spostando la logica per un
public static IDictionary<string,object> MergeDataAttributes(
this HtmlHelper htmlHelper,
object htmlAttributes,
object dataAttributes)
e chiamarlo come
<%= Html.TextBox ("textBox", "Value",
Html.MergeDataAttributes(new { title = "Some ordinary attribute" }, new { myid = m.ID })) %>
Vedere questa domanda "Attributi html sillabati con asp.net mvc" http://stackoverflow.com/questions/2897733/hyphenated-html-attributes-with-asp-net-mvc/12091886#12091886 –
nota: il più recente la risposta corretta è http: // stackoverflow.it/a/5872576/1037948, più in basso in questa pagina se non ti piace lo scorrimento;) – drzaus