質問

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?

役に立ちましたか?

解決

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

他のヒント

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"}) %>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top