In my MVC application, I am facing an issue with the left menu. I want the active link's CSS to remain styled even after a page reload.
Within my CSS file, I have defined the following styles:
.navleft li a:hover {
background: url('../Content/images/nav.png') no-repeat;
background-position: -232px 0;
color: #fff;
left: -6px;
padding: 19px 18px 19px 40px;
margin-top: -10px;
}
.navleft li a:active {
background: url('../Content/images/nav_active.png') no-repeat;
background-position: -232px 0;
color: #fff;
left: -6px;
padding: 19px 18px 19px 40px;
margin-top: -10px;
}
In my view file, I am dynamically generating the menu using the following code:
<ul class="navleft">
@foreach (var item in Model.CLeftMenu.ToList())
{
foreach (var content in Model.LeftSiteContent.ToList())
{
if (item.LeftMenuID == content.LeftMenuID)
{
<li><a href="@Url.Action("Details", "LeftContents", new { id = @content.LeftContentID })">@item.LeftMenuTitle</a></li>
}
}
}
</ul>
The hover effect works fine on the menu, but the active state is not being applied correctly. When inspecting the page, it shows:
<a href="/LeftContents/Details/4" class="active">Services</a>
It seems that the "active" class is automatically added. To make it work as intended, I had to update my CSS to:
.active {
background: url('../Content/images/nav_active.png') no-repeat;
background-position: -232px 0;
color: #fff;
left: -6px;
padding: 19px 18px 19px 40px;
margin-top: -10px;
}
However, this change affected all active links across the site. Is there a way to apply this style only to the left menu without causing conflicts? Do I need to declare "current" as well for proper functionality?
I came across a solution for a similar problem in this Stack Overflow post, but it did not work in my case.
Thank you for any suggestions or assistance.