Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 297
John Allers Avatar asked Feb 03 '11 16:02

John Allers


1 Answers

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.

like image 57
Darin Dimitrov Avatar answered Sep 19 '22 19:09

Darin Dimitrov