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 - |
質問
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?
解決
他のヒント
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"}) %>
所属していません StackOverflow