I have the following project structure:
/Views/Shared/_Layout;
/Areas/Area1/Views/ControllerName/Index;
...
Is there any way to force all areas to use the _Layout as a base layout?
Is there any way to do it without adding the _ViewStart file (for example, via the routing configuration)?
See Also:
How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?
The _ViewStart. cshtml page is a special view page containing the statement declaration to include the Layout page. Instead of declaring the Layout page in every view page, we can use the _ViewStart page. When a View Page Start is running, the “_ViewStart. cshtml” page will assign the Layout page for it.
So, the _layout. cshtml would be a layout view of all the views included in Views and its subfolders. Setting Layout View in _ViewStart.cshtml. The _ViewStart. cshtml can also be created in the sub-folders of the View folder to set the default layout page for all the views included in that particular subfolder.
Right click the Views\HelloWorld folder and click Add, then click MVC 5 View Page with Layout (Razor). In the Specify Name for Item dialog box, enter Index, and then click OK. In the Select a Layout Page dialog, accept the default _Layout. cshtml and click OK.
You just have to add a file named:
_ViewStart.cshtml
Under each area views folder:
/Areas/Area1/Views/_ViewStart.cshtml
And edit the file to point to the root layout like this:
@{ Layout = "~/Views/Shared/_Layout.cshtml"; }
In order for this to work, you do not have to specify a value in the view's layout property, if you do, you would be overriding the global layout
Note: As Tony mentioned, you could edit each view's layout property to point to the root layout, however this is not the recommended way to do it since you would be coupling your views with your layout and change it would be painful
If you would like to use code to set the default view's layout, perhaps you should consider writing a custom view engine.
Try to google about custom RazorViewEngine
and RazorView
This article could be a good start point
http://weblogs.asp.net/imranbaloch/archive/2011/06/27/view-engine-with-dynamic-view-location.aspx
I have not done something like this but I hope I'm pointing you in the right direction
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With