0

In my _Layout.cshtml page, I have a list item in the main navigation bar. I want to show a css class depending on the current route. For example, if the user is at www.website.com/Notifications, I want to add the class to the Notifications list item. This is my attempt. It does not work:

<li><a asp-page="/Notifications" class="@(<%=Url.RequestContext["id"]%>  == "Notifications" ? Html.Raw("selected-club") : Html.Raw(""))"><i class="fas fa-home"></i> Notifications</a></li>

How can I get the current page ID from the layout file, considering that it doesn't have a page model?

Martin Erlic
  • 5,467
  • 22
  • 81
  • 153

1 Answers1

4

try the below codes that gets the current controller and action by RouteData values from the ViewContext

 <body>
    @{
        string controller = "";
        string action = "";

        if (ViewContext.RouteData.Values["controller"] != null)
        {
            controller = ViewContext.RouteData.Values["controller"].ToString();
        }

        if (ViewContext.RouteData.Values["action"] != null)
        {
            action = ViewContext.RouteData.Values["action"].ToString();
        }
    }

    <div class="float-right">
                <section id="login">
                    @Html.Partial("_LoginPartial")
                </section>
                <nav>
                    <ul id="menu">
                        <li>@Html.ActionLink("Home", "Index", "Home")</li>
                        @if (controller.ToLower() == "home" && action.ToLower() == "about")
                        {
                        <li>@Html.ActionLink("About", "About", "Home")</li>
                        }
                        <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    </ul>
                </nav>
            </div>
giri-webdev
  • 525
  • 10
  • 20
  • you can use null propagator to save those 4 lines of code on top. – Anirudha Gupta May 15 '18 at 07:02
  • Hm.. I'm getting ``NullReferenceException: Object reference not set to an instance of an object. MenuApp.WebPlatform.Application.Pages._Layout_View+<b__81_21>d.MoveNext() in _Layout.cshtml, line 63`` – Martin Erlic May 15 '18 at 10:10