1

Consider the following valid razor HTML helper code:

@Html.TextBoxFor(m => m.Name, new { @class = "form-control", placeholder="Select..." })

However, there are some libraries that I'm using, that uses hyphenated attributes such as this:

<select class="form-control select2me" data-placeholder="Select...">

When I try to do this:

@Html.TextBoxFor(m => m.Name, new { @class = "form-control", data-placeholder="Select..." })

I get this error:

Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

How can I use hyphenated attributes in razor synax?

TheGeekZn
  • 3,696
  • 10
  • 55
  • 91
Null Reference
  • 11,260
  • 40
  • 107
  • 184

2 Answers2

3

Use an underscore _ - the Razor engine is smart enough to translate that to a data- attribute.

Tieson T.
  • 20,774
  • 6
  • 77
  • 92
0

From This answer:

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 attributes.

<%= Html.TextBox("name", value, new { @data_foo = "bar"}) %>
Community
  • 1
  • 1
TheGeekZn
  • 3,696
  • 10
  • 55
  • 91