Use an underscore _
- the Razor engine is smart enough to translate that to a data-
attribute.
Using hyphenated HTML attributes in MVC
-
17-07-2023 - |
Domanda
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?
Soluzione
Altri suggerimenti
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"}) %>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow