In einem aktuellen Projekt von mir habe ich es mit HtmlHelper Erweiterungen und Daten aus der ViewContext.RouteData.Values Sammlung.
So eine einfache Erweiterung wie dieses Gebäude aus:
public static string OnClass(this HtmlHelper html, bool isOn)
{
if (isOn)
return " class=\"on\"";
return string.Empty;
}
Sie können eine beliebige Anzahl von Kombinationen aufbauen, z.B.
gerade die Prüfung der aktuellen Aktion:
public static string OnClass(this HtmlHelper html, string action)
{
string currentAction = html.ViewContext.RouteData.Values["action"].ToString();
return html.OnClass(currentAction.ToLower() == action.ToLower());
}
Testing für eine Reihe von Aktionen:
public static string OnClass(this HtmlHelper html, string[] actions)
{
string currentAction = html.ViewContext.RouteData.Values["action"].ToString();
foreach (string action in actions)
{
if (currentAction.ToLower() == action.ToLower())
return html.OnClass(true);
}
return string.Empty;
}
Testing für Aktion und Controller:
public static string OnClass(this HtmlHelper html, string action, string controller)
{
string currentController = html.ViewContext.RouteData.Values["controller"].ToString();
if (currentController.ToLower() == controller.ToLower())
return html.OnClass(action);
return string.Empty;
}
usw., usw.
Dann rufen Sie einfach es aus Ihrer Sicht (en) wie so
<ul id="left-menu">
<!-- simple boolean -->
<li <%= Html.OnClass(something == somethingElse) %>>Blah</li>
<!-- action -->
<li <%= Html.OnClass("Index") %>>Blah</li>
<!-- any number of actions -->
<li <%= Html.OnClass(new string[] { "Index", "Details", "View" }) %>>Blah</li>
<!-- action and controller -->
<li <%= Html.OnClass("Index", "Home") %>>Blah</li>
</ul>
Welche auch immer man es betrachtet, Htmlhelper Erweiterungen sind dein Freund!
:-)
HTHS
Charles
Verwandte: http://stackoverflow.com/questions/906423/jquery-add-class-on-current-item –
@ Robert - Art, aber ich möchte ein Nicht-Javascript-Lösung. Ich würde im Idealfall denken, da ich alle Informationen habe, die ich auf dem Server brauche, könnte ich dies auf dem Server tun. – Martin