How to use multiple layout files in a single MVC application

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

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 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 above code, a View associated with an Action method from 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