Spase Markovski
Spase Markovski

Reputation: 683

How can I make a small change to a Razor Layout from a ViewPage in MVC?

I want to add a class to a ul.li navigational item, called ".current". All of the navigational items are located in _layout.cshtml and I am kinda at lost of what is the best way of specifying the ".current" class.

Here is a picture of my desired navigation (https://i.sstatic.net/glkYD.png):

enter image description here

Note that whenever the User is in Company->Overview or Company->Settings; I basically want the ".current" class to be added the their parent ul.li item called "Company". This adds that visual cue (white triangle) on the right side of the section.

For this reason this stackoverflow thread, couldn't quite help me.

Any help is appreciated, thanks!

Upvotes: 0

Views: 118

Answers (2)

Paul
Paul

Reputation: 12440

you may be able to base this on the URL it self like so:

public static IHtmlString MenuLink(this HtmlHelper htmlHelper, string text, string url)
    {
        var link = new TagBuilder("a");
        link.Attributes.Add("href", url);
        string currentUrl = HttpContext.Current.Request.RawUrl;
        if (string.Equals(url, currentUrl, StringComparison.OrdinalIgnoreCase))
        {
            link.AddCssClass("current");
        }

        link.InnerHtml = text;
        return new HtmlString(link.ToString());
    }

You would use it like so:

@Html.MenuLink("About", "/home/about")
@Html.MenuLink("Contact", Url.Action("Contact", "Home"))

Upvotes: 1

Jason
Jason

Reputation: 1226

You can handle this with JQuery:

$(".current").removeClass("current");
$("#someID").addClass("current");

The first line will remove the 'current' class from anything that already has it. The second line will assign the 'current' class to an element with the specified id.

Upvotes: 0

Related Questions