如何在ASP.NET Core Razor页面中使用_ViewStart设置条件布局? [英] How can I set up conditional Layouts with _ViewStart in ASP.NET Core Razor Pages?

查看:175
本文介绍了如何在ASP.NET Core Razor页面中使用_ViewStart设置条件布局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想基于当前渲染的页面显示不同的布局.

I want to display different layouts based on the current rendered Page.

我在网上找不到任何相关信息,但我觉得这应该是一个非常普遍的用例.

I can't find anything online about this but I feel like this should be an extremely common use case.

我只有几页.我想为注册"和登录"页面分配唯一的布局.

I only have a few pages. I would like to assign unique layouts to both my Register and Login pages.

这是到目前为止,但是在这种情况下我无法使用ControllerContext.

This is what I've got so far but I am unable to use the ControllerContext in this situation.

@{
    string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
    dynamic Layout;
    switch (controllerName)
    {
        case "Register":
            Layout = "_RegisterLayout";
            break;
        case "Login":
            Layout = "_LoginLayout";
            break;
        default:
            Layout = "_Layout";
            break;
    }
}

推荐答案

为方便起见,_ViewStart文件用于为ViewStart所在的同一文件夹中的所有页面及其所有子文件夹设置布局.您可以通过多种方法来覆盖它,但是在这种情况下,最简单的方法是为Razor页面本身中的 Layout 属性指定一个不同的值:

As a convenience, the _ViewStart file is used to set the layout for all pages in the same folder as the ViewStart, and all its subfolders. You can override that in a number of ways, but the simplest way in your case is to specify a different value for the Layout property in the Razor Page itself:

@page
@model MyApp.Pages.Account.LoginModel
@{
    Layout = "/path/to/login-layout.cshtml;
}
<h1>Login</h1>
...

这篇关于如何在ASP.NET Core Razor页面中使用_ViewStart设置条件布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆