Rendering Layouts Based on a Condition in ASP.Net MVC

Introduction

The layout page (_layout.cshtml) represents the layout of each page in the MVC application. This is very similar to Master Page in ASP.NET application. Layout page is located within a shared folder inside the view folder. The Layout page helps us to maintain a consistent look and feel within an application.

Problem statement

Can we change the layout page at runtime or based on the condition in our MVC application?

Solution

This is possible with a MVC application. There are many ways to do this. In this article I will explain the solution one by one.

Example

Suppose I have two layout pages (_layout.chtml and _otherLayout.cshtml). Based on some condition I want to render the layout page.

layout page

1. Rendering layout page from ActionResult (using Controller. View extension method)

The Controller. View method has two extension methods, using these extension methods we can pass a master page (layout page) name and render a layout page based on a condition.
 
render layout page base on condition 
 
ActionResult 
 
Example Code
  1. public ActionResult About()  
  2. {  
  3.     return View("About","_otherLayout");  
  4. }   
  5.   
  6. public ActionResult OtherAbout()  
  7. {  
  8.     string myName = "Jignesh Trivedi";  
  9.     return View("About""_otherLayout", myName);  
  10. } 

2. Using _ViewStart.cshtml Page

The _ViewStart.cshtml file executes before the rendering of each view. This means that any code within this file will execute before any code in the view. This page helps us when we want to set or apply something before the view render. _ViewStart.cshtml page used to define the default layout page for the MVC application.

Using the _ViewStart.cshtml page, we can change the layout page based on a condition.

Example Code

  1. @{     
  2. var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();  
  3.     string layout = "";  
  4.     if (controller != "Home")  
  5.     {  
  6.         layout = "~/Views/Shared/_otherLayout.cshtml";  
  7.     }  
  8.     else  
  9.     {  
  10.         layout = "~/Views/Shared/_Layout.cshtml";  
  11.     }  
  12.     Layout = layout;  
  13. }  

 

We can also create multiple _ViewStart.cshtml pages. The file execution is dependent upon the location of the file within the folder hierarchy and the view being rendered. The MVC Runtime will first execute the code of the _ViewStart.cshtml file located in the root of the Views folder.

Views folder

3. Define the Layout page in each view

We can override the default layout rendering by setting the Layout property of the View using the following code.

  1. @{     
  2.     Layout = "~/Views/Shared/_otherLayout.cshtml";  
  3.     ViewBag.Title = "About Us";  
  4. }  

 

Summary

Using the method described above we can render layouts based on a condition in ASP.NET MVC.


Similar Articles