Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>
</div>

here is Index page which assigns value to viewBag

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading