loki
loki

Reputation: 2966

How to set css class 'active' by using C#?

I would like to add a css class to <li class=''></li> item. Can you help?

public static string IsMenuActive(Blms.Model.MenuItem menuItem)
{
        string result = "";

        if (System.Web.HttpContext.Current.Request.ServerVariables["Url"].ToLower().IndexOf(GetMenuLink(menuItem).ToLower()) >= 0)
            result = "active";

        if (string.IsNullOrEmpty(result)) {
            foreach (var child in menuItem.Children)
            {
                if (System.Web.HttpContext.Current.Request.ServerVariables["Url"].ToLower().IndexOf(GetMenuLink(child).ToLower()) >= 0)
                {
                    result = "active";
                    break;
                }
            }
        }

        return result;
    }

HTML side:

 <li class="@Blms.Web.Core.MenuUtilities.GetMenuLiClass(menuItem) @Blms.Web.Core.MenuUtilities.IsMenuActive(menuItem)">

Upvotes: 0

Views: 751

Answers (1)

Wouter van der Houven
Wouter van der Houven

Reputation: 448

Try using a custom htmlhelper to solve this problem. It will result in a cleaner view.

https://www.simple-talk.com/dotnet/asp.net/writing-custom-html-helpers-for-asp.net-mvc/

Upvotes: 1

Related Questions