119

Is there a nicer syntax when creating elements with hyphenated attributes instead of using:

<%= Html.TextBox ("name", value, new Dictionary<string, object> { {"data-foo", "bar"} }) %>

Looking at the HTML specs for the proposed standards HTML 5 and WIA ARIA it seems hyphens in HTML attributes are being planned to be more common as some sort of simple name spacing.

E.g. HTML 5 proposes custom attributes are prefixed with data- and WIA ARIA uses the aria- prefix for all WIA ARIA attributes.

When using HTML helpers in ASP.NET MVC such as <%= Html.TextBox("name", value, new { attribute = attributeValue }) %> the anonymous object is converted to a dictionary.

Unfortunately in C# there is no support for hyphens in names, so the only alternative is to create a dictionary. The syntax for which is very verbose, has anyone seen a nicer alternative or a simple way of altering the functionality of ASP.NET MVC's HTML extensions without having to re-write the entire extension?

Chris Chilvers
  • 6,429
  • 3
  • 32
  • 53

2 Answers2

215

Use an underscore in the data attribute name, and it'll magically 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 attribute names.

<%= Html.TextBox("name", value, new { @data_foo = "bar"}) %>
ED-209
  • 4,706
  • 2
  • 21
  • 26
  • 2
    I found a similar problemin several SO questions, and this is the best answer. – user2780436 Jan 01 '15 at 20:44
  • 1
    Could you add the reason for your statement **underscores aren't valid in html attributes**. At least [html 4.01 states](http://www.w3.org/TR/html401/intro/sgmltut.html#didx-attribute): _The attribute value may only contain letters (a-z and A-Z), digits (0-9), hyphens (ASCII decimal 45), periods (ASCII decimal 46), underscores (ASCII decimal 95), and colons (ASCII decimal 58)_, – surfmuggle Jul 15 '15 at 19:12
  • 1
    @threeFourOneSixOneThree your quote refers to the attribute value, but in this question we're referring to attribute names. – ED-209 Jul 16 '15 at 08:40
  • 1
    @threeFourOneSixOneThree I have changed the end of my answer to 'underscores aren't valid in html attribute names' – ED-209 Jul 16 '15 at 08:42
19

The answer provided at ActionLink htmlAttributes suggests using underscores instead of hyphens. MVC.Net is supposed to emit hyphens instead of the underscores when sending the page to the browser.

Community
  • 1
  • 1
Zarepheth
  • 2,465
  • 2
  • 32
  • 49