Change class in layout file mvc4
asp.net-mvc-3, asp.net-mvc-4, c#
Solution
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.
Problem
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?