34

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?

2
  • what happens when you put @ infront of your attribute name? if you want to add an attribute of class you need to type @class because class is special, would this also apply to your special attribute? Commented Feb 3, 2011 at 16:39
  • Putting @ in front has the same behavior as not having it there. Commented Feb 3, 2011 at 16:49

1 Answer 1

54

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately it doesnt work with Html.BeginForm() so we had to do it this way @using (Html.BeginForm("view", "controller", FormMethod.Post,new Dictionary<string, object>{{ "data-test", "testdata" }} ))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.