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?
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";
}
}
Also,you can use
@{
Layout="xxx"
}
to set diiferent layout in different pages as David Tansey
said.