_Layout
is like a masterpage in ASP.NET webforms. If you want to apply a common theme (menu, styles ..) across many pages then _Layout
file is the best place to put into.
You can have one single _Layout file for the entire application or one each for each specific module of the application.
_ViewStart
file has the reference to the _Layout page used in the application.
If you use the below code then the respective page resets the layout to null and does not render the layout defined in _ViewStart
. Code in _ViewStart
file gets executed at the start of each View.
@{
Layout = null;
}
If you want any specific layout in a page overriding the default layout defined int _ViewStart
then you can do as below
@{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_OtherLayout.cshtml";
}
You don't need to explicitly set the Layout in any of the individual view files unless if you want to override the default layout defined in _ViewStart
.
Or if you want the _ViewStart
to decide which layout page to render based on the controller then you can write something like below in _ViewStart
page. The view will have the respective layout themes applied when rendered.
@{
var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
string layout = "";
if (controller == "ReportController")
{
layout = "~/Views/Shared/_ReportsLayout.cshtml";
}
else
{
layout = "~/Views/Shared/_Layout.cshtml";
}
Layout = layout;
}