문제

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