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

本文关键字:动态 设置 @class ActionLink Html MVC | 更新日期: 2023-09-27 18:05:40

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

我想做

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

但是运行时在我的语法上爆炸了

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

假设您希望"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"})
@Html.ActionLink("Pricing", "Index", "Pricing", 
new { PageIndex = 2, @class = (ViewBag.PageIndex == 2)? "" : "ActiveMenuItem" },
 null)