MVC - 如何在Html.ActionLink中动态设置@class

时间:2011-08-16 15:10:20

标签: c# asp.net-mvc-3 razor

如何在ActionLink中动态设置@class?

我想做

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

但是运行时会破坏我的语法。

2 个答案:

答案 0 :(得分:6)

假设你想让“class”成为一个HTML属性而将“PageIndex”作为一个动作参数,你可以这样做:

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

MUSEFAN编辑:

你仍然可以像这样使用ActionLink ......

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

答案 1 :(得分:4)

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