【问题标题】:Adding a hyphen to the html attribute name using MVC3 WebGrid helper使用 MVC3 WebGrid 帮助器向 html 属性名称添加连字符
【发布时间】: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


【解决方案1】:

恐怕这是不可能的。不幸的是,WebGrid 不支持与标准 HTML 帮助器相同的语法,例如 TextBoxFor,您可以:

@Html.TextBoxFor(x => x.SomeProp, new { data_test = "testdata" })

下划线会自动转换为破折号。

【讨论】:

  • 不幸的是它不适用于 Html.BeginForm() 所以我们不得不这样做 @using (Html.BeginForm("view", "controller", FormMethod.Post,new Dictionary{{ "data-test", "testdata" }} ))
猜你喜欢
  • 2011-06-19
  • 2011-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-27
  • 2014-01-26
  • 1970-01-01
相关资源
最近更新 更多