Search code examples
c#asp.net-mvcrazoractionlink

How to display active actionlink in MVC


I have some actionlinks in my _Layout.cshtml view as follows:

    <li>@Html.ActionLink("Signup", "Signup", "Home")</li>
    <li>@Html.ActionLink("Login", "Login", "Home")</li>
    <li>@Html.ActionLink("Home", "Index", "Home")</li>

I want to show Signup action link in another color when it is selected. how can I do this in ASP.NET MVC?


Solution

  • Simply use the values contained in ViewContext.RouteData, namely the Action and Controller values. We could build on what you currently have with something like this

      <li class=@(ViewContext.RouteData.Values["Action"].ToString() == "Signup" ? "active" : "")>@Html.ActionLink("Signup", "Signup", "Home")</li>
      <li class=@(ViewContext.RouteData.Values["Action"].ToString() == "Login" ? "active" : "")>@Html.ActionLink("Login", "Login", "Home")</li>
      <li class=@(ViewContext.RouteData.Values["Action"].ToString() == "Index" ? "active" : "")>@Html.ActionLink("Home", "Index", "Home")</li>
    

    if you need controller means just check the condition

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