Waqar Ul Khaf Waqar Ul Khaf - 3 months ago 37
ASP.NET (C#) Question

How to use ViewContext?

I have layout page in asp.net MVC application and this page contains a navbar

<ul class="sidenavbar">
<li><a style="font-size:large">ASP.NET Tutorial</a></li>
<li>@Html.ActionLink("Home","Home")</li>
<li>@Html.ActionLink("Introduction", "Introduction")</li>
<li>@Html.ActionLink("Getting Started", "GettingStarted")</li>
</ul>


See I have actionmethod for each item in my navbar now I want to apply css class active to currently selected list item how can I achieve this using ViewContext or if there is any better way?

Answer

This may work

<ul class="nav navbar-nav">
  <li class="@(ViewContext.RouteData.Values["controller"].ToString() == "Home" ? "active" : "")">@Html.ActionLink("Home", "Index", "Home")</li>
  <li class="@(ViewContext.RouteData.Values["controller"].ToString() == "About" ? "active" : "")">@Html.ActionLink("About", "About", "Home")</li>
  <li class="@(ViewContext.RouteData.Values["controller"].ToString() == "Contact" ? "active" : "")">@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>