6

Previously I have created C# applications using MVC and it is possible to specify the layout view to use on the view in it's file. Such that the view file contains:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

/*Rest of file*/

Recently I have started creating applications using razor pages. So far I only have a single layout page. However, I would like to use a different layout page for a subset of pages, and I can only see how to specify a single layout page for all pages within the Pages folder. As the layout is declared in the _ViewStart.cshtml file. Where the contents of this file is simply:

@{
    Layout = "_Layout";
}

Is there a way of using one layout file for some pages, and then a different layout files for other pages?

penguin178
  • 344
  • 1
  • 3
  • 20
  • https://stackoverflow.com/questions/39870298/how-do-i-specify-different-layouts-in-the-asp-net-core-mvc – David Tansey Mar 17 '21 at 16:51
  • This looks like it changed from .Net Framework to .Net Core, is that right? Rather than MVC & Razor? I switched from .Net Framework MVC to .Net Core Razor in one go, so I'm not always sure which part changed where. – penguin178 Mar 17 '21 at 16:59
  • It does appear to have changed. I would focus on the answer in that post provided by @Sanket. That approach makes the most sense to me. Your mileage may vay. – David Tansey Mar 17 '21 at 17:02

2 Answers2

9

If you want to using one layout file for some pages, and then a different layout files for other pages.you can try to get the current url in _ViewStart.cshtml,then check the url and set Layout page.Here is a demo:

_ViewStart.cshtml(Page1 and Page2 will set Layout = "_Layout";,and the other page will set Layout = "_Layout1";):

@{
    var routeUrl = ViewContext.RouteData.Values["Page"].ToString();
    //you can put pages' name into pages
    var pages = new List<string> { "Page1", "Page2"};
    //if routeUrl contains any of pages,the page will use _Layout as Layout page,the other pages will use _Layout1 ad Layout page
    if (pages.Any(routeUrl.Contains))
    {
        Layout = "_Layout";
    }
    else {
        Layout = "_Layout1";
    }

}

result: enter image description here

Also,you can use

@{
   Layout="xxx"
}

to set diiferent layout in different pages as David Tansey said.

Yiyi You
  • 16,875
  • 1
  • 10
  • 22
3

There are multiple ways to accomplish this:

  1. Even if you've registered single layout in ViewStart.cshtml you can still use different layout on specific page like:

    Layout = "~/Views/Shared/_Layout2.cshtml";

  2. You can use either ViewData or ViewBag to assign the layout value and use that in your cshtm file

  3. You can add a check to identity which layout you need to use:

.....

@{
    if (User.IsInRole("Admin"))
    {
        Layout = "_AdminLayout";
    }
    else
    {
        Layout = "_Layout";
    }
}
Ask
  • 3,076
  • 6
  • 30
  • 63