Я не вижу способа заставить объявление анонимного типа принять 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 } ) ) %>