【问题标题】:C# - Conditionally loading a specific footer w/ a switch statementC# - 有条件地加载带有 switch 语句的特定页脚
【发布时间】:2020-04-06 08:17:55
【问题描述】:

在我的_Layout.cshtml 文件中,我使用 switch 语句有条件地加载 CSS 文件。如果 url 包含 collAcollD,则加载 New.css。如果没有,则加载 Old.css。它有效,我很高兴。

我想对NewFooterOldFooter 做同样的事情,如果网址包含collA,则加载新的,否则加载旧的。

但是根据 switch 语句的位置,如果我有条件地加载任一页脚,那么它们将被放置在 上方 页眉。我希望页脚在页面底部呈现。

最初我有第二个 switch 语句,有条件地将页脚加载到正确的位置,但我只想使用 一个 switch。

基本上,我想要实现三件事:

  1. 我想使用加载 CSS 文件的相同 switch 语句有条件地加载 NewFooterOldFooter
  2. 我希望页脚加载到页面底部,而不是页眉上方
  3. 我只想使用一个 switch 语句

PS - 我对 ASP.NET 和 C# 还很陌生,所以请记住我的语法很生疏。


Layout.cshtml

<title>@ViewBag.Title</title>

    @{
        var keywords = new[] { "colls/collA", "colls/collD" };
        var isNew = RenderPage("~/Views/Shared/NewFooter.cshtml");
        var isOld = RenderPage("~/Views/Shared/OldFooter.cshtml");

        switch (keywords.FirstOrDefault(Request.RawUrl.ToLower().Contains))
        {
            case "colls/collA":
            case "colls/collD":
                @Styles.Render("~/Content/New.css"); // CSS bundle
                //@isNew; // the issue here is that the NewFooter renders above the header
                break;
            default:
                @Styles.Render("~/Content/Old.css");
                //@isOld;
                break;
        }
    }

    @Scripts.Render("~/bundles/jquery")
// other bundles here

...
...
...

<body>
    @if (!Request.Browser.IsMobileDevice)
    {
        // navbar and body code

<div class="body-content">
    @RenderBody()
    // this is where the second switch statement used to be, where the new/old footers were rendered
</div>

...
...
...

</body>

【问题讨论】:

  • 为什么要一个开关?
  • 嗨@Him,当我有第二个switch语句时,这意味着复制case "colls/collA"colls/collD。计划是添加更多案例(每个案例代表一个页面),因此拥有第二个切换意味着更多的工作。
  • 虽然我认为整个做法是错误的,你可以简单地添加一个标志bool isNewFooter = false;,然后在开关内标记它true。在页脚处,只需检查 isNewFooter 是否为 true 并相应地显示页脚。
  • 嘿,我按照您的指示进行了操作。如果您将评论添加为答案,那么我会接受。谢谢!

标签: c# html asp.net razor switch-statement


【解决方案1】:

您应该创建一个字符串actualURL,然后在开关内分配它。 您可以在页脚中呈现它(@RenderBody() 下方)。

【讨论】:

    猜你喜欢
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 2015-11-05
    • 1970-01-01
    相关资源
    最近更新 更多