Nie widzę żadnego sposobu uzyskania anonimowej deklaracji typu, aby zaakceptować data-myid
, ponieważ nie jest to poprawna nazwa właściwości w języku C#. Jedną z możliwości byłoby, aby utworzyć nowy przeciążenie, że trwa dodatkowy dataAttributes
parametr, a poprzedza data-
do nazw dla Ciebie ...
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);
}
}
}
}
Następnie można dodać atrybut data-myid
z
<%= Html.TextBox ("textBox", "Value",
new { title = "Some ordinary attribute" },
new { myid = m.ID }) %>
jednak , który pozostawia cię do stworzenia tego przeciążenia na jakichkolwiek innych metodach, które chcesz zaakceptować atrybutów danych, co jest uciążliwe. Można obejść, że przesuwając logikę do
public static IDictionary<string,object> MergeDataAttributes(
this HtmlHelper htmlHelper,
object htmlAttributes,
object dataAttributes)
i nazywają go jako
<%= Html.TextBox ("textBox", "Value",
Html.MergeDataAttributes(new { title = "Some ordinary attribute" }, new { myid = m.ID })) %>
Zobacz pytanie "Dzielenie się atrybutami html z asp.net mvc" http://stackoverflow.com/questions/2897733/hyphenated-html-attributes-with-asp-net-mvc/12091886#12091886 –
uwaga: nowsza poprawną odpowiedzią jest http: // stackoverflow.com/a/5872576/1037948, dalej w dół tej strony, jeśli nie lubisz przewijania;) – drzaus