如何将 class 属性添加到由 MVC 的 HTML Helpers 生成的 HTML 元素? [英] How can I add a class attribute to an HTML element generated by MVC's HTML Helpers?
问题描述
ASP.NET MVC 可以使用 HTML Helpers 生成 HTML 元素,例如 @Html.ActionLink()
、@Html.BeginForm()
等.>
我知道我可以通过创建一个匿名对象来指定表单属性 并将该对象传递给(本例中的第四个)htmlAttributes
参数,其中为元素指定 id
:
Html.BeginForm("Foo", "Bar", FormMethod.Post, new { id = "MyForm"})
但是 class
属性呢?显然这不起作用:
Html.BeginForm("Foo", "Bar", FormMethod.Post, new { class = "myclass"})
因为当我的视图被请求时,它只会抛出随机的语法错误,因为它在遇到 C# 关键字 class
后需要其他东西.
我也试过:
new { _class = "myclass"}
和
new { class_ = "myclass"}
但它们也不起作用,因为下划线被破折号替换.
我知道我也可以手工编写 HTML 元素或将表单包装在 <div class="myClass">
中,但我仍然有兴趣知道它应该如何完成.
为了创建具有 保留关键字 作为它在 C# 中的名称,您可以在属性名称前加上 at 符号 @代码>:
Html.BeginForm("Foo", "Bar", FormMethod.Post, new { @class = "myclass"})
对于 VB.NET 此语法将 使用点.
完成,在该语言中,它是所有匿名类型:
Html.BeginForm("Foo", "Bar", FormMethod.Post, new with { .class = "myclass" })
ASP.NET MVC can generate HTML elements using HTML Helpers, for example @Html.ActionLink()
, @Html.BeginForm()
and so on.
I know I can specify form attributes by creating an anonymous object and pass that object for the (fourth in this case) htmlAttributes
parameter where specifying an id
for the element:
Html.BeginForm("Foo", "Bar", FormMethod.Post, new { id = "MyForm"})
But what about the class
attribute? Obviously this does not work:
Html.BeginForm("Foo", "Bar", FormMethod.Post, new { class = "myclass"})
As that just throws random syntax errors when my view is requested, because it expects something else after encountering the C# keyword class
.
I've also tried:
new { _class = "myclass"}
and
new { class_ = "myclass"}
But they also did not work, as the underscores get replaced by dashes.
I know that I can just as well write the HTML elements by hand or wrap the form inside a <div class="myClass">
, but I'd still be interested to know how it is supposed to be done.
In order to create an anonymous type (or any type) with a property that has a reserved keyword as its name in C#, you can prepend the property name with an at sign, @
:
Html.BeginForm("Foo", "Bar", FormMethod.Post, new { @class = "myclass"})
For VB.NET this syntax would be accomplished using the dot, .
, which in that language is default syntax for all anonymous types:
Html.BeginForm("Foo", "Bar", FormMethod.Post, new with { .class = "myclass" })
这篇关于如何将 class 属性添加到由 MVC 的 HTML Helpers 生成的 HTML 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!