petko_stankoski
petko_stankoski

Reputation: 10713

Add css class to < li > in controller method

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?

Upvotes: 1

Views: 1337

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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>

Upvotes: 4

Related Questions