Change class in mvc4 layout file
I have a layout page that consists of standard headers and footers and a function RenderBody()
. My header consists of navigation with big buttons at the top like modules in the system
Customer Quote Jobs etc
My question is that I want these buttons to activate the activity class on load, depending on what was clicked on. Do I need to do this in javascript or can I still pass model data or some kind of variable to the layout file to set this?
source to share
For this I use the following function:
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;
}
This is an extension method that I store in a file HtmlExtensions.cs
. 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>
Possibly a better solution, but it works for me. In short, you have to study HttpContext
your page.
source to share
I use the following approach to highlight the selected menu item:
<ul class="menu">
@{Dictionary<string, string> menuList = new Dictionary<string, string>() {
{ "Customer", "Customer" },
{ "Quote", "Quote" },
{ "Jobs", "Jobs" },
{ "etc", "etc" },
};
}
@foreach (var item in menuList )
{
<li @(Request.ServerVariables["SCRIPT_NAME"].Contains(item.Key) ? " class=active" : string.Empty)>
<a href="/Home/@item.Key">@item.Value</a></li>
}
</ul>
Where item.Key is for action names, item.Value for the corresponding name in the menu.
source to share