.NET: Inline IF Statements to Echo Out Class Value Based on MVC Action Name

12/28/2015 10:17:36 PM

The following can be used to programmatically set a css class value based on the current action.

@{    
    string currentAction = ViewContext.RouteData.Values["action"].ToString().ToLower();
}

<ul class="navigation">
    <li class="@(currentAction == "index" ? "selected" : "")"><a href="/home/">My Home</a></li>
    <li class="@(currentAction == "users" ? "selected" : "")"><a href="/home/users/">Users</a></li>
    <li class="@(currentAction == "groups" ? "selected" : "")"><a href="/home/groups/">Groups</a></li>
    <li class="@(currentAction == "settings" ? "selected" : "")"><a href="/home/settings/">Settings</a></li>
</ul>