【问题标题】:How can I retrieve the current route from the _Layout.cshtml file in my ASP.NET project? [duplicate]如何从我的 ASP.NET 项目中的 _Layout.cshtml 文件中检索当前路由? [复制]
【发布时间】:2018-10-24 19:49:57
【问题描述】:

在我的 _Layout.cshtml 页面中,我在主导航栏中有一个列表项。我想根据当前路线显示一个 css 类。例如,如果用户在 www.website.com/Notifications,我想将该类添加到 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?

【问题讨论】:

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


    【解决方案1】:

    尝试以下代码,通过 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>
    

    【讨论】:

    • 您可以使用空传播器将这 4 行代码保存在顶部。
    • 嗯.. 我收到NullReferenceException: Object reference not set to an instance of an object. MenuApp.WebPlatform.Application.Pages._Layout_View+&lt;&lt;ExecuteAsync&gt;b__81_21&gt;d.MoveNext() in _Layout.cshtml, line 63
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    相关资源
    最近更新 更多