Ich kann keine Möglichkeit sehen, eine anonyme Typdeklaration zu akzeptieren data-myid
, da das ist kein gültiger Eigenschaftenname in C#. Eine Möglichkeit wäre, eine neue Überlastung zu schaffen, die einen zusätzlichen dataAttributes
Parameter übernimmt, und prepends data-
den Namen für Sie ...
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);
}
}
}
}
Dann können Sie ein data-myid
Attribut mit
<%= Html.TextBox ("textBox", "Value",
new { title = "Some ordinary attribute" },
new { myid = m.ID }) %>
fügen jedoch Das lässt Sie diese Überladung für alle anderen Methoden erstellen, die Sie Datenattribute akzeptieren möchten, was ein Schmerz ist. Sie könnten um das erhalten, indem die Logik zu einem es
public static IDictionary<string,object> MergeDataAttributes(
this HtmlHelper htmlHelper,
object htmlAttributes,
object dataAttributes)
bewegen und rufen als
<%= Html.TextBox ("textBox", "Value",
Html.MergeDataAttributes(new { title = "Some ordinary attribute" }, new { myid = m.ID })) %>
Sehen Sie diese Frage ‚Gekoppelte HTML-Attribute mit asp.net MVC‘ http://stackoverflow.com/questions/2897733/hyphenated-html-attributes-with-asp-net-mvc/12091886#12091886 –
Anmerkung: die neueren Die richtige Antwort lautet http: // stackoverflow.com/a/5872576/1037948, weiter unten auf dieser Seite, wenn Sie nicht gerne scrollen;) – drzaus