2

how to put class="active" within <li> depending on selected controller?

<li  ><a href="@Url.Action("index", "Home")">Home</a></li>
<li  ><a href="@Url.Action("index", "Car")">Cars</a></li>

Blessings

1 Answer 1

1

I generally create an action link html helper for accomplishing this task. Note, that I mark the link itself as "selected" vs the list item.

public static class ActionLinkHelpers
{
    public static MvcHtmlString SelectedActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName)
    {
        var controller = (string) helper.ViewContext.RouteData.Values["controller"];
        if (string.Compare(controller, controllerName, StringComparison.InvariantCultureIgnoreCase) == 0)
        {
            return helper.ActionLink(linkText, actionName, controllerName, null, new { Class = "selected" }); 
        }

        return helper.ActionLink(linkText, actionName, controllerName);
    }
}

After you have an action link helper setup within your project your list would look as follows:

<li>@Html.SelectedActionLink("Home", "index", "Home")</li>
<li>@Html.SelectedActionLink("Cars", "index", "Car")</li>

EDIT:

In order to use a custom helper MVC must be aware of it. Add a new folder to your project "HtmlHelpers" for example and place this class inside of it. From there you need to add a line to the /Views/Web.config:

<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="YourNameSpace.HtmlHelpers"/>
  </namespaces>
</pages>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks friend, what are the libraries to implement class SelectedActionLink?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.