【发布时间】:2011-06-20 19:16:40
【问题描述】:
我在尝试将自定义 HTML5 数据属性添加到使用 WebGrid 帮助程序呈现的表时遇到问题。我希望表格标签如下所示:
<table data-test="testdata"><!-- Table Content --></table>
这是使用 Razor 视图引擎的示例视图:
@{
var myUser = new
{
Id = 1,
Name = "Test User"
};
var users = new[] { myUser };
var grid = new WebGrid(users);
}
@grid.GetHtml(htmlAttributes: new { data-test = "testdata"})
最后一行将产生一个“无效的匿名类型成员声明器”。错误,因为 data-test 中的连字符。
使用其他一些输入 HtmlHelpers,您可以使用下划线代替连字符,并且在呈现时它会自动更改为连字符。 WebGrid 不会发生这种情况。
如果我传入 htmlAttributes 的字典:
@grid.GetHtml(htmlAttributes: new Dictionary<string, object> {{ "data-test", "testdata"}})
表格被渲染成这样:
<table Comparer="System.Collections.Generic.GenericEqualityComparer`1[System.String]" Count="1" Keys="System.Collections.Generic.Dictionary`2+KeyCollection[System.String,System.Object]" Values="System.Collections.Generic.Dictionary`2+ValueCollection[System.String,System.Object]"><!-- Table Content --></table>
我做错了什么,我应该怎么做才能根据需要渲染属性?
【问题讨论】:
-
将
@放在属性名称前会发生什么?如果你想添加一个类的属性,你需要输入@class,因为class是特殊的,这是否也适用于你的特殊属性? -
将@ 放在前面与没有放在前面的行为相同。
标签: asp.net-mvc asp.net-mvc-3 html-helper