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
 

public ActionResult About()
{
    return View("About","_otherLayout");

public ActionResult OtherAbout()
{
    string myName = "Jignesh Trivedi";
    return View("About", "_otherLayout", myName);
}

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

@{   
var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
    string layout = "";
    if (controller != "Home")
    {
        layout = "~/Views/Shared/_otherLayout.cshtml";
    }
    else
    {
        layout = "~/Views/Shared/_Layout.cshtml";
    }
    Layout = layout;
}

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.

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

Summary

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

Up Next
    Ebook Download
    View all
    Learn
    View all