How to use multiple layout pages in MVC application?

In this blog, we will see how to use multiple Layout page in MVC application.
Layout pages are used to share common designs across all view pages. For eg, header and footer are generally common across the application. In this case, the Layout page is useful.

What is a Layout page in MVC?

A layout page helps us to maintain a consistent look throughout the application. The layout page is similar to a master page in traditional ASPX web forms.

Recently, I came across the below interview Questions on MVC and thought to share via my blog

Q. Can we use multiple Layout pages in a single MVC application?

Yes, we can use multiple Layout in ASP.Net MVC application.

By default, Visual Studio adds a Layout page in a shared folder which can be used by other View pages if required. In some cases, we can have the requirement to use multiple shared layout pages in MVC application.
For example – Layout for home page and Layout for inner pages.

Q. How can we use multiple shared Layout pages in MVC application?

We can define multiple layouts for a single MVC application with _ViewStart.cshtml file.

Let’s demonstrate this –

I have used 2 Layout pages in one MVC application by using _ViewStart.cshtml file.
_ViewStart file is basically is used to define the common Layout page for all the Views.
For more details, read my previous blog – “What is _ViewStart file?

1. Create an MVC project
2. Add 2 Layout pages in the Shared folder. (See below screenshot.)

3. Add 2 Controllers in Controllers folder (See below screenshot.)

4. Now add _ViewStart.cshtml file. To see how to add _ViewStart.cshtml file, visit this link – _ViewStart file in MVC

5. Once _ViewStart.cshtml file added, remove the existing content from this file and add below snippet.

    string CurrentControllerName = Convert.ToString(HttpContext.Current.Request.RequestContext.RouteData.Values[“Controller”]); 
    switch (CurrentControllerName) 
        case “Product”:
            Layout = “~/Views/Shared/_Layout.cshtml”; 
            Layout = “~/Views/Shared/_Layout1.cshtml”; 

So, as per the above code, a View associated with an Action method from the Product controller will render _Layout.cshtml. And a View associated with an Action method from Default1 controller will render _Layout1.cshtml.
You can have multiple switch cases as per your need.

Summary –

MVC allows to use multiple layouts in a single application. With _ViewStart.cshtml file we can define more that one layout files for our MVC application.

Hope this blog helps you.

Fe other blogs on MVC you would love to read –

Follow – SharePointCafe.Net

Please follow and like us:

Leave a Comment