JSLint исторически был основным инструментом для этого, но несколько больше теперь существуют:
Самый простой способ - получить текущий контроллер и действие из RouteData ViewContext. Обратите внимание на изменение сигнатуры и использование символа @ для экранирования ключевого слова.
<% var controller = ViewContext.RouteData.Values["controller"] as string ?? "Home";
var action = ViewContext.RouteData.Values["action"] as string ?? "Index";
var page = (controller + ":" + action).ToLower();
%>
<%= Html.ActionLink( "About", "About", "Home", null,
new { @class = page == "home:about" ? "current" : "" ) %>
<%= Html.ActionLink( "Home", "Index", "Home", null,
new { @class = page == "home:index" ? "current" : "" ) %>
Обратите внимание, что вы можете объединить это расширение HtmlHelper, как @ Jon, и сделать его более чистым.
<%= Html.MenuLink( "About", "About", "Home", null, null, "current" ) %>
Где MenuActionLink -
public static class MenuHelperExtensions
{
public static string MenuLink( this HtmlHelper helper,
string text,
string action,
string controller,
object routeValues,
object htmlAttributes,
string currentClass )
{
RouteValueDictionary attributes = new RouteValueDictionary( htmlAttributes );
string currentController = helper.ViewContext.RouteData.Values["controller"] as string ?? "home";
string currentAction = helper.ViewContext.RouteData.Values["action"] as string ?? "index";
string page = string.Format( "{0}:{1}", currentController, currentAction ).ToLower();
string thisPage = string.Format( "{0}:{1}", controller, action ).ToLower();
attributes["class"] = (page == thisPage) ? currentClass : "";
return helper.ActionLink( text, action, controller, new RouteValueDictionary( routeValues ), attributes );
}
}
Недавно я создал помощник HTML для этого, который выглядит так:
public static string NavigationLink(this HtmlHelper helper, string path, string text)
{
string cssClass = String.Empty;
if (HttpContext.Current.Request.Path.IndexOf(path) != -1)
{
cssClass = "class = 'selected'";
}
return String.Format(@"<li><a href='{0}' {1}>{2}</a></li>", path, cssClass, text);
}
Реализация выглядит так:
<ul id="Navigation">
<%=Html.NavigationLink("/Path1", "Text1")%>
<%=Html.NavigationLink("/Path2", "Text2")%>
<%=Html.NavigationLink("/Path3", "Text3")%>
<%=Html.NavigationLink("/Path4", "Text4")%>
</ul>
Возможно, это 5-й параметр, поэтому вставьте ноль перед атрибутом html. Этот пост здесь описывает это как таковое, хотя вы можете передать некоторые вещи по 4-му аргументу, 5-й предназначен специально для атрибутов HTML