How to use multiple layout files in a single MVC application


In this blog, we will see how to use more than one Layout file or multiple Layout files in a single 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.

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

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

Q. Can we use more than one Layout in a single MVC application?

Answer - Yes, we can use multiple Layout in one 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 requirement to use multiple Layout pages.
For eg - Layout for home page and Layout for inner pages.

Q. How can we use multiple Layout in a single MVC application?

Let's demonstrate this -

I have used 2 Layout in one MVC application by using _ViewStart.cshtml file.
_ViewStart file is basically is used to define 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"
            break
        default:
            Layout = "~/Views/Shared/_Layout1.cshtml"
            break
    } 
}


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 multiple switch cases as per your need.

Hope this blog helps you.

Fe other blogs on MVC you would love to read -

Follow - SharePointCafe.Net


Comments

Popular