MVC - How to dynamically set @class in Html.ActionLink

How can I dynamically set @class in ActionLink?

I want to make

@Html.ActionLink("Pricing", "Index", "Pricing", new { PageIndex = 2, @(ViewBag.PageIndex == 2 ? @class="" : @class="ActiveMenuItem" )}, null) 

But the runtime explodes in my syntax.

+4
source share
2 answers

Assuming you want the "class" to be an attribute of HTML, and "PageIndex" to be an action parameter, you can do this instead:

 <a href="@Url.Action("Index", "Pricing")?PageIndex=2" class="@(ViewBag.PageIndex == 2 ? "ActiveMenuItem" : "")">Pricing</a> 

MUSEFAN EDIT:

You can still use ActionLink like this ...

 @Html.ActionLink("Pricing", "Index", "Pricing", new {PageIndex = 2}, new {@class = ViewBag.PageIndex == 2 ? "" : "ActiveMenuItem"}) 
+6
source
 @Html.ActionLink("Pricing", "Index", "Pricing", new { PageIndex = 2, @class = (ViewBag.PageIndex == 2)? "" : "ActiveMenuItem" }, null) 
+4
source

All Articles