Tôi không thể thấy bất kỳ cách nào để nhận tuyên bố loại ẩn danh để chấp nhận data-myid
vì đó không phải là tên thuộc tính hợp lệ trong C#. Một lựa chọn sẽ là để tạo ra một tình trạng quá tải mới mà sẽ đưa thêm một tham số dataAttributes
, và prepends data-
với tên cho bạn ...
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);
}
}
}
}
Sau đó, bạn có thể thêm một thuộc tính data-myid
với
<%= Html.TextBox ("textBox", "Value",
new { title = "Some ordinary attribute" },
new { myid = m.ID }) %>
Tuy nhiên , điều đó khiến bạn tạo ra tình trạng quá tải trên bất kỳ phương pháp nào khác mà bạn muốn chấp nhận các thuộc tính dữ liệu, đó là một nỗi đau. Bạn có thể nhận được xung quanh đó bằng cách di chuyển logic để một
public static IDictionary<string,object> MergeDataAttributes(
this HtmlHelper htmlHelper,
object htmlAttributes,
object dataAttributes)
và gọi nó như
<%= Html.TextBox ("textBox", "Value",
Html.MergeDataAttributes(new { title = "Some ordinary attribute" }, new { myid = m.ID })) %>
Xem câu hỏi này 'Thuộc tính html bị ngắt quãng với asp.net mvc' http://stackoverflow.com/questions/2897733/hyphenated-html-attributes-with-asp-net-mvc/12091886#12091886 –
lưu ý: mới hơn câu trả lời chính xác là http: // stackoverflow.com/a/5872576/1037948, xa hơn trang này nếu bạn không thích cuộn;) – drzaus