Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change class in layout file mvc4

I have a layout page which consists of the standard Header and Footer and the RenderBody() function. My Header consists of a navigation with big buttons across the top as modules in the system

Customer    Quote    Jobs     etc

My question is I want to be able to give these buttons a class of active on load depending on which has been clicked. Do I need to do this in javascript or is there anyway I can pass model data or some variable to the layout file to set this?

like image 221
CR41G14 Avatar asked Dec 10 '25 20:12

CR41G14


1 Answers

I use the following function to achieve this:

public static string MarkActive<TModel>(this HtmlHelper<TModel> html,string url)
{
    if (html.ViewContext.HttpContext.Request.Url.LocalPath
        .ToLower().StartsWith(url.ToLower().Trim()))
        return "active";
    else
        return null;
}

It is an extension method I keep in a HtmlExtensions.cs file. I use it like this:

<ul>
    <li class="@Html.MarkActive("/home")"><a href="/home">Home</a></li>
    <li class="@Html.MarkActive("/microsite"><a href="/microsite">View Microsite</a></li>
    <li class="@Html.MarkActive("/settings")"><a href="/settings/">Settings</a></li>
    <li><a href="/account/logout">Log out</a></li>
</ul>

There is probably a better solution, but this works for me. In short, you should examine the HttpContext of your page.

like image 88
Oliver Avatar answered Dec 12 '25 10:12

Oliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!