如何从ASP.NET项目中的_Layout.cshtml文件中检索当前路径?

时间:2018-05-15 04:35:10

标签: c# asp.net .net asp.net-mvc

在我的_Layout.cshtml页面中,我在主导航栏中有一个列表项。我想根据当前路线显示一个css类。例如,如果用户在www.website.com/Notifications,我想将该类添加到通知列表项。这是我的尝试。它不起作用:

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

如果它没有页面模型,我如何从布局文件中获取当前页面ID?

1 个答案:

答案 0 :(得分:3)

尝试以下代码,通过ViewContext

中的RouteData值获取当前控制器和操作
 <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>