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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With