使用MVC3 WebGrid帮助程序在html属性名称中添加连字符

Joh*_*ers 30 asp.net-mvc html-helper asp.net-mvc-3

我在尝试将自定义HTML5数据属性添加到使用WebGrid帮助器呈现的表时遇到问题.我希望表标签看起来如下:

<table data-test="testdata"><!-- Table Content --></table>
Run Code Online (Sandbox Code Playgroud)

以下是使用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"})
Run Code Online (Sandbox Code Playgroud)

最后一行将生成"无效的匿名类型成员声明符".错误,因为数据测试中的连字符.

对于其他一些输入HtmlHelpers,您可以使用下划线代替连字符,并且在渲染时它将自动更改为连字符.WebGrid不会发生这种情况.

如果我传入htmlAttributes的字典:

@grid.GetHtml(htmlAttributes: new Dictionary<string, object> {{ "data-test", "testdata"}})
Run Code Online (Sandbox Code Playgroud)

表格如下呈现:

<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>
Run Code Online (Sandbox Code Playgroud)

我做错了什么,我该怎么做才能根据需要渲染属性?

Dar*_*rov 47

我担心这是不可能的.不幸的是,WebGrid不支持与标准HTML帮助程序相同的语法,例如TextBoxFor你可以:

@Html.TextBoxFor(x => x.SomeProp, new { data_test = "testdata" })
Run Code Online (Sandbox Code Playgroud)

并且下划线将自动转换为破折号.

  • 不幸的是它不能用于Html.BeginForm()所以我们必须这样做@using(Html.BeginForm("view","controller",FormMethod.Post,new Dictionary <string,object> {{"data-test) ", "测试数据" }} )) (14认同)