MikeDub MikeDub - 1 year ago 122
C# Question

How to specify global MVC layout without specifying layout path in razor view

I'm trying to get away from having to manually specify the layout path in every Razor view that I have / create.

So in a razor view, you would normally specify the view / layout properties such as:

ViewBag.Title = "About Us";
Layout = "~/Views/Shared/_ContentLayout.cshtml";

I have a base controller that all my controllers are inheriting, in which I would love to be able to specify the layout at this level, or alternatively in app_start etc.

For any exceptions I would just override this in the view itself.

After an extensive search, I haven't found any evidence of anyone being able to do this yet.

My current, next-best workaround is to specify this in the ViewBag, to keep it dynamic, but I still need to put a declaration in the view:

Layout = ViewBag.Layout;

Is it possible? Solutions?

Answer Source

Reference: http://weblogs.asp.net/scottgu/asp-net-mvc-3-layouts

Since MVC3 there is a convention where...

You can add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:

The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the _ContentLayout.cshtml file by default:

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

Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download