John Allers
John Allers

Reputation: 3122

Adding a hyphen to the html attribute name using MVC3 WebGrid helper

I'm having a problem trying to add a custom HTML5 data attribute to the table that is rendered using the WebGrid helper. I want the table tag look as follows:

<table data-test="testdata"><!-- Table Content --></table>

Here is a sample view using the Razor view engine:

@{
    var myUser = new
    {
        Id = 1,
        Name = "Test User"
    };

    var users = new[] { myUser };

    var grid = new WebGrid(users);
}
@grid.GetHtml(htmlAttributes: new { data-test = "testdata"})

The last line will produce a "Invalid anonymous type member declarator." error, because of the hyphen in data-test.

With some of the other input HtmlHelpers, you can use an underscore in place of the hyphen and it will be automatically changed to a hyphen when rendered. This does not happen with the WebGrid.

If I pass in a dictionary for htmlAttributes:

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

the table gets rendered as such:

<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>

What am I doing wrong and what should I do render the attribute as desired?

Upvotes: 34

Views: 14329

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039598

I am afraid that this is not possible. Unfortunately the WebGrid it doesn't support the same syntax as standard HTML helper such as TextBoxFor where you could:

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

and the underscore would be automatically converted to dash.

Upvotes: 54

Related Questions