我了解到few minutes ago添加数据属性是向html元素添加自定义信息的好方法。所以我试着这样做:
<%= Html.TextBox ("textBox", "Value", new { data-myid = m.ID })%>
但最终会出现语法错误。如何定义自定义数据属性?
编辑:
我看到我可以使用以下方式实现此效果:
<%= Html.TextBox ("textBox", "Value", new Dictionary<string, object> {{ "data-myid", m.ID }})%>
但那看起来并不......嗯......干净!有没有更好的方法呢?
答案 0 :(得分:106)
使用下划线而不是破折号。
new { data_myid = m.ID }
这个肯定适用于MVC3 (尚未检查其他版本)。在呈现HTML时,下划线将转换为破折号。
修改
这也适用于最新版本的MVC。
答案 1 :(得分:5)
我看不到任何方法来获取匿名类型声明来接受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 } ) ) %>
答案 2 :(得分:0)
我认为你必须创建自己的助手来为你做这件事。我无法在视图中找到直接执行此操作的方法。
答案 3 :(得分:-1)
<%= Html.TextBox ("myTextBox", "",
new { @class="redText", title="Enter red text here"})%>
结果:
<input type="text" id="myTextBox" class="redText" title="Enter red text here" />
我不确定你的问题是什么。可能与您的匿名类型的属性名称中的“ - ”有关。
是的,编译器不喜欢你的属性名称。从注释中,为了添加html5数据属性,您必须使用字典或创建另一个简化字典构造的扩展。