我怎么能一个类属性添加到由MVC的HTML辅助生成的HTML元素? [英] How can I add a class attribute to an HTML element generated by MVC's HTML Helpers?
问题描述
ASP.NET MVC可以使用HTML辅助生成HTML元素,例如 @ Html.ActionLink()
, @ Html.BeginForm()
等。
ASP.NET MVC can generate HTML elements using HTML Helpers, for example @Html.ActionLink()
, @Html.BeginForm()
and so on.
我知道我可以指定形式通过创建匿名对象并通过该属性对象的(第四次在这种情况下) htmlAttributes
参数,其中指定 ID
的元素:
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"})
由于在请求我的看法,只是抛出随机语法错误,因为它需要别的东西遇到C#关键字后类
。
我也试过:
new { _class = "myclass"}
和
new { class_ = "myclass"}
但他们也没有工作,因为下划线得到由破折号取代。
我知道我可以只以及手工编写HTML元素或包裹一个&LT内部的形式; DIV CLASS =MyClass的>
,但我ð仍然有兴趣知道它是如何应该做。
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.
推荐答案
为了创建具有的保留关键字作为其在C#中的名称,可以prePEND与at符号属性名, @
:
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"})
有关VB.NET <一个href=\"http://stackoverflow.com/questions/1444495/how-do-i-apply-a-css-class-to-html-actionlink-in-asp-net-mvc\">this语法将使用点来完成的,。
,这在该语言是的 所有的匿名类型的:
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" })
这篇关于我怎么能一个类属性添加到由MVC的HTML辅助生成的HTML元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!