您可以编写自定义帮助方法来生成这些菜单项并检查当前操作和控制器并应用正确的 CSS 类。您可以查看 以下示例并根据您的要求对其进行调整。
就像这样:
public static class MenuExtensions
{
public static IHtmlString MenuItem(
this HtmlHelper htmlHelper,
string text,
string action,
string controller
)
{
var li = new TagBuilder("li");
var routeData = htmlHelper.ViewContext.RouteData;
var currentAction = routeData.GetRequiredString("action");
var currentController = routeData.GetRequiredString("controller");
if (string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) &&
string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase))
{
li.AddCssClass("activeLink");
}
li.InnerHtml = htmlHelper.ActionLink(text, action, controller, null, null).ToHtmlString();
return new HtmlString(li.ToString());
}
}
然后在你看来:
<table id="myTable">
<tr>
<td>
<ul>
@Html.MenuItem("Home", "Index", "Home")
@Html.MenuItem("About", "About", "Home")
@Html.MenuItem("Another", "Index", "Another")
</ul>
</td>
</tr>
</table>
现在,如果用户当前正在浏览控制器 ( ) 的About
操作,将生成以下标记:Home
/Home/About
<table id="myTable">
<tr>
<td>
<ul>
<li><a href="/">Home</a></li>
<li class="activeLink"><a href="/Home/About">About</a></li>
<li><a href="/Another">Another</a></li>
</ul>
</td>
</tr>
</table>