Hyphenated html attributes with asp.net mvc

C#asp.net Mvc

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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"}) %>

Solution 2 - C#

The answer provided at https://stackoverflow.com/questions/4108943/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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChris ChilversView Question on Stackoverflow
Solution 1 - C#ED-209View Answer on Stackoverflow
Solution 2 - C#ZarephethView Answer on Stackoverflow