Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How can I dynamically set @class in an ActionLink?

I want to do

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

But the runtime blows up on my syntax.

like image 912
P.Brian.Mackey Avatar asked Dec 28 '22 15:12

P.Brian.Mackey


2 Answers

Assuming you want "class" to be an HTML attribute 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 an ActionLink like this...

@Html.ActionLink("Pricing", "Index", "Pricing", new {PageIndex = 2}, new {@class = ViewBag.PageIndex == 2 ? "" : "ActiveMenuItem"})
like image 155
musefan Avatar answered Dec 30 '22 04:12

musefan


@Html.ActionLink("Pricing", "Index", "Pricing", 
new { PageIndex = 2, @class = (ViewBag.PageIndex == 2)? "" : "ActiveMenuItem" },
 null)
like image 39
Jamie Dixon Avatar answered Dec 30 '22 05:12

Jamie Dixon