Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

asp.net mvc - How can I add a class attribute to an HTML element generated by MVC's HTML Helpers?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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" })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...