1

In my _Layout.cshtml file I have:

<table id="myTable">
        <tr><td><ul><li id="id1"><a href="@Url.Action("Index", "Home")">Home</a></li>
                    <li id="id2"><a href="@Url.Action("Index", "About")">About</a></li>
                    <li id="id3"><a href="@Url.Action("Index", "Another")">Another</a></li>
        </ul></td></tr>
</table>

The active link (the one in the url in the browser), should have css class "activeLink". How to add the css class to the correct link via code in the controllers (not client-side)? How to catch the correct < li >? Do I need to do this in the Index methods in all of the controllers?

1 Answer 1

4

You could write a custom helper method to generate those menu items and which checks the current action and controller and applies the correct CSS class. You could take a look at the following example and adapt it to your requirements.

Just like that:

public static class MenuExtensions
{
    public static IHtmlString MenuItem(
        this HtmlHelper htmlHelper,
        string text,
        string action,
        string controller
    )
    {
        var li = new TagBuilder("li");
        var routeData = htmlHelper.ViewContext.RouteData;
        var currentAction = routeData.GetRequiredString("action");
        var currentController = routeData.GetRequiredString("controller");
        if (string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) &&
            string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase))
        {
            li.AddCssClass("activeLink");
        }

        li.InnerHtml = htmlHelper.ActionLink(text, action, controller, null, null).ToHtmlString();
        return new HtmlString(li.ToString());
    }
}

and then in your view:

<table id="myTable">
    <tr>
        <td>
            <ul>
                @Html.MenuItem("Home", "Index", "Home")
                @Html.MenuItem("About", "About", "Home")
                @Html.MenuItem("Another", "Index", "Another")
            </ul>
        </td>
    </tr>
</table>

Now, if the user is currently browsing the About action of Home controller (/Home/About), the following markup will be generated:

<table id="myTable">
    <tr>
        <td>
            <ul>
                <li><a href="/">Home</a></li>
                <li class="activeLink"><a href="/Home/About">About</a></li>
                <li><a href="/Another">Another</a></li>
            </ul>
        </td>
    </tr>
</table>
Sign up to request clarification or add additional context in comments.

Comments

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.