You could write a custom helper method:
public static MvcHtmlString 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("selected");
}
li.SetInnerText(text);
return MvcHtmlString.Create(li.ToString());
}
and then:
<ul>
@Html.MenuItem("Home", "home", "home")
@Html.MenuItem("About", "about", "home")
@Html.MenuItem("Contact", "contact", "home")
@Html.MenuItem("Blog", "blog", "home")
</ul>
The helper check the current action and controller and if they match the one passed as arguments to the helper it appends the selected
CSS class to the li
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…