Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you specify a css class name on ActionLinks in Razor?

The following code generates an error:

@Html.ActionLink("Title", "action", new { id=1 }, new { @class = "myCssClass" }); 

I tried to use @ since class is a keyword. How should I write it when using razor?

Edit

The problem was not really the at sign, but that I didn't use blocks together with my if:

@if (blabla)     @Html.ActionLink("Title", "action", new { id=1 }, new { @class = "myCssClass" }); 

Works:

@if (blabla) {     @Html.ActionLink("Title", "action", new { id=1 }, new { @class = "myCssClass" }); } 

Up voted both answers since they made me realize the problem.

like image 674
jgauffin Avatar asked Dec 17 '10 09:12

jgauffin


People also ask

How do I add a class to ActionLink?

If you do not want to pass in a variable you can do the following: Html. ActionLink("View Performances", "Details", "Productions", null, new {@class = "button"}) if you just want to add the class. Also, the "Productions" part of this element is not required.

What is Razor syntax in MVC?

Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.


2 Answers

Try to write something like:

@(Html.ActionLink("Title", "action", new { id=1 }, new { @class = "myCssClass" })); 

There is a good post about Razor related to your problem: ScottGu Blog

like image 199
Aleksei Anufriev Avatar answered Oct 10 '22 05:10

Aleksei Anufriev


Simply:

@Html.ActionLink("Title", "action", new { id=1 }, new { @class = "myCssClass" }) 

will work in ASP.NET MVC 3 RC2. Razor is intelligent.

like image 26
Darin Dimitrov Avatar answered Oct 10 '22 06:10

Darin Dimitrov