Adding class to div based on ViewBag.Title value in _layout.cshtml file

I am working on a asp .net razor page application . I have a navbar in _layout.cshtml file which contain some links. I want to assign active class to link which is clicked. I am trying to do so by verifying value of ViewBag.Title but its not working but I am getting its value in console. Please help me.
Here is my navbar link part in _layout.cshtml file.

  <div class="navbar-nav ms-auto">
                        <a data-toggle="tab" asp-page="Index" class="nav-item nav-link   @ViewBag.Title=='Welcome'? ' active' : '' ">Home</a>
                        <a data-toggle="tab"  asp-page="Products" class="nav-item nav-link {{ @ViewBag.Title=='Products'  ? 'active' : '' }}">Products</a>
                        <a data-toggle="tab" asp-page="NewsBlog" class="nav-item nav-link {{ @ViewBag.Title=='News & Blog'  ? 'active' : '' }} ">News &amp; Blog</a>
                        <a data-toggle="tab" asp-page="Contact" class="nav-item nav-link {{ @ViewData["Title"]=='Contact us'  ? 'active' : '' }}">Contact Us</a>

here is Index page which assigns value to viewBag

@model Sora.UI.Pages.IndexModel
     ViewBag.Title= "Welcome";

>Solution :

The @ sign inserts a peice of razor syntax. That’s actually C# code not javascript.

With the straight syntax you can only access properties and fields like @Viewbag.myprop. However you can also evaluate (c#!) expressions when putting the code between parentheses. E.g.

@(ViewBag.Title=="Welcome" ? " active" : "")

Note: this requires the whole expression in a single line. Multi line expressions will not work.

Leave a Reply