您可以編寫一個自定義幫助器方法來生成這些菜單項,並檢查當前操作和控制器並應用正確的CSS類。您可以查看following example並根據您的要求進行調整。
就像這樣:
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>
,如果用戶當前瀏覽Home
控制器(/Home/About
)的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>