Saturday, 2 June 2012

Using hyphenated data attributes in MVC

In .net MVC this doesn't work:
@Html.TextBox("name", null, new { @class = "input-xlarge", @data-input = "75"})
The hyphenated 'data-input' attribute causes the error "Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access." Well, as of MVC 3, you can actually use an underscore instead, like so:
@Html.TextBox("name", null, new { @class = "input-xlarge", @data_input = "75"})
And it'll handle it for you, converting it to a hyphen. It knows you want a hyphen rather than an underscore as underscores aren't valid in html attributes. Lucky huh?

1 comment:

  1. Thanks Ed. It's these little things that are often the difficult things to figure out. Your post saved me a fair bit of time wondering why my hyphens were causing such a problem. Cheers,



Comments are moderated, so you'll have to wait a little bit before they appear!