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

Time:06-24

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 >
                        <a data-toggle="tab" asp-page="Index" >Home</a>
                        <a data-toggle="tab"  asp-page="Products" >Products</a>
                        <a data-toggle="tab" asp-page="NewsBlog" >News &amp; Blog</a>
                        <a data-toggle="tab" asp-page="Contact" 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";
}

CodePudding user response:

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.

  • Related