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.

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 the below interview Questions on MVC and thought to share via my blog -

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

Answer - 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 eg - Layout for home page and Layout for inner pages.

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

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 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