我看不到任何方法可以让匿名类型声明接受data-myid,因为这不是 C# 中的有效属性名称。一种选择是创建一个新的重载,该重载采用额外的dataAttributes 参数,并为您的名称添加data-...
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);
}
}
}
}
然后你可以添加一个data-myid属性
<%= Html.TextBox ("textBox", "Value",
new { title = "Some ordinary attribute" },
new { myid = m.ID }) %>
但是,这会让您在要接受数据属性的任何其他方法上创建该重载,这很痛苦。您可以通过将逻辑移至
public static IDictionary<string,object> MergeDataAttributes(
this HtmlHelper htmlHelper,
object htmlAttributes,
object dataAttributes)
并将其称为
<%= Html.TextBox ("textBox", "Value",
Html.MergeDataAttributes( new { title = "Some ordinary attribute" }, new { myid = m.ID } ) ) %>