Hyphenated html attributes with asp.net mvc
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 开发者_如何学JAVAplanned 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?
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"}) %>
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.
精彩评论