0

I have a layout for my web application, which loads different menu items based on which language the user has configured on his/her profile and if the user isn't logged in, they also get different links. The list of items is returned to each view.

The problem occurs when I try to combine this with javascript, to make the currently visited link active.

Each time the layout is loaded the menu is overwritten with the following code

 @foreach (var item in ViewBag.LoggedIn)
 {
   <li><a href="@item.Url">@item.Text</a></li>
 }

I tried to use the following code to make the links active.

$('li > a').click(function () {
    $('li').removeClass();
    $(this).parent().addClass('active');
 });

All help will be greatly appreciated.

Atle Kristiansen
  • 707
  • 7
  • 28

2 Answers2

1

I suggest you try to render the menu based on the current url and set the active at the moment of rendering:

string url = HttpContext.Current.Request.Url.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx You can conviniently get a substring of this

 @foreach (var item in ViewBag.LoggedIn)
 {
   @if (item.Url == url)
   {
   <li class="active"><a href="@item.Url">@item.Text</a></li>
   }
   else
   {
    <li><a href="@item.Url">@item.Text</a></li>
   }
 }
Albondi
  • 1,141
  • 1
  • 8
  • 19
  • Does this work with asp.net core? If so, what do I need to include in the view to make "HttpContext.Current.Request.Url.AbsoluteUri" available? – Atle Kristiansen Feb 20 '19 at 19:36
  • You can use [@Context.Request.Host @Context.Request.Path](https://stackoverflow.com/questions/38437005/how-to-get-current-url-in-view-in-asp-net-core-1-0) – Albondi Feb 20 '19 at 19:42
0

You need to remove the active class if present on any li and then add active to the clicked one.

$('li > a').click(function (e) {
 e.preventDefault();
    $('li').removeClass('active')
    $(this).parent().addClass('active')
})
.active {
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="root">
  <li><a href="#">Menu 1</a></li>
  <li><a href="#">Menu 2</a></li>
  <li><a href="#">Menu 3</a></li>
  <li><a href="#">Menu 4</a></li>
  <li><a href="#">Menu 5</a></li>
</div>
swapnesh
  • 26,318
  • 22
  • 94
  • 126