As a student who is new to ASP.NET MVC and coming from ASP.NET Web Forms, I am accustomed to it.
Here is the list:
<ul class="sidebar bg-grayDark">
<li class="active">
<a href="@Url.Action("Index", "Home")">
<span class="mif-home icon"></span>
<span class="title">Home</span>
</a>
</li>
<li class="bg-hover-black">
<a href="@Url.Action("Index", "Product")">
<span class="mif-shop icon"></span>
<span class="title">Products</span>
<span class="counter">14</span>
</a>
</li>
<li class="bg-hover-black">
<a href="@Url.Action("Index", "Category")">
<span class="mif-flow-cascade icon"></span>
<span class="title">Categories</span>
<span class="counter">9</span>
</a>
</li>
<li class="bg-hover-black">
<a href="@Url.Action("Index", "User")">
<span class="mif-users icon"></span>
<span class="title">Users</span>
<span class="counter">1</span>
</a>
</li>
</ul>
My objective: When a view is rendered, I want to add "active" to the that has been clicked on. For example, if I click on "Category", then the active class should be removed from Home and added to Category. The same applies for "bg-hover-black".
I initially attempted to achieve this using JavaScript:
$(function () {
$('.sidebar').on('click', 'li', function () {
if (!$(this).hasClass('active')) {
$('.sidebar li').removeClass('active');
$(this).addClass('active');
}
})
})
However, this approach did not work as expected because when the page loads, the HTML is re-rendered with "active" for the Home section. Removing "active" from Home would result in nothing being active onClick, except between clicks and page load.
Do you have any solutions? I have searched extensively online but haven't found anything helpful.
Apologies for any English errors, I am still learning :).
Thank you,
Hellcat8.