ViewStart in ASP.NET Core MVC

ViewStart in ASP.NET Core MVC Application

In this article, I will discuss the ViewStart in ASP.NET Core MVC Web Application with Examples. Please read our previous article before proceeding to this article, as it is a continuation part of our previous article. Please read our previous article discussing the Sections in Layout View in ASP.NET Core MVC Application. As part of this article, we will discuss the following pointers.

  1. Why Do We Need _ViewStart.cshtml File in ASP.NET Core MVC Application?
  2. What is _ViewStart.cshtml File in ASP.NET Core MVC?
  3. How to Create _ViewStart.cshtml file in ASP.NET Core MVC Application?
  4. How to Set the Layout Property in ViewStart.cshtml file?
  5. Understanding the Hierarchy of _ViewStart.cshtml File in ASP.NET Core MVC.
  6. How to Use a Different Layout Other the Layout Specified in the _ViewStart.cshtml File?
  7. How Do We Select a Layout Conditionally in the ViewStart file?
  8. When to Use _ViewStart.cshtml File in ASP.NET Core MVC?
Why Do We Need _ViewStart.cshtml File in ASP.NET Core MVC Application?

The _ViewStart.cshtml file in ASP.NET Core MVC is a special file that plays an important role in the application’s view rendering pipeline. Its primary purpose is to define common settings that apply to all views in the application, ensuring consistency across the application’s UI and reducing code duplication.

For example, as of now, we have used the Layout Property to associate a view with a layout view, as shown below. So, basically, within the Child view, we have added the following statement to use the layout view.
Layout = “~/Views/Shared/_Layout.cshtml”;

Suppose we have 100 views in our application, and all the 100 views want to use the same layout file. Then we need to set the Layout Property, i.e., Layout = “~/Views/Shared/_Layout.cshtml”; in all the 100 views. This violates the DRY (Don’t Repeat Yourself) Principle and has disadvantages.

  1. Redundant Code
  2. Maintenance Overhead

Suppose tomorrow you want to use a different Layout for all those 100 views, then you need to update the Layout Property in each and every individual view of your application. This process is tedious, time-consuming, and error-prone because you may miss updating the Layout Property in some views. To solve the above problems, we need to use the _ViewStart.cshtml file. Here are several reasons why the _ViewStart.cshtml file is needed:

  • Layout Specification: It allows developers to specify a common layout file for all views within an application or a specific folder. By setting the layout in _ViewStart.cshtml, you ensure that all views use the same layout without having to specify it explicitly in each view.
  • Code Reusability: It helps reduce code duplication by allowing common code to be written in one place and applied to multiple views. For instance, if you need to set a particular layout, define common namespaces, or set other properties that should be applied to all views, _ViewStart.cshtml is the place to do it.
  • Consistent Look and Feel: Ensuring that all views use the same layout and settings (e.g., stylesheets, scripts) helps maintain a consistent look and feel across the application.
  • Centralized View Settings: It provides a centralized place to manage settings that affect the views. For example, setting up the ViewData dictionary with data that should be available to all views, like site-wide configuration settings or SEO meta tags.
What is _ViewStart.cshtml File in ASP.NET Core MVC Application?

The _ViewStart.cshtml file in ASP.NET Core MVC plays an important role in the application’s views management, acting as a common layout initializer for the views within an application. Its primary function is to set layout properties shared across multiple views, promoting a DRY (Don’t Repeat Yourself) principle by avoiding the redundancy of specifying the same layout information in every view file.

The code present in this file will be executed before the code in an individual view is executed. So, you can set the Layout Property in this file as shown below instead of setting the Layout Property in each individual view, which is going to be executed before the actual view is executed, and set the Layout view.

_ViewStart.cshtml file in ASP.NET Core MVC Application

Once you set the Layout Property in _ViewStart.cshtml file as shown in the above image, maintaining the application becomes much easier. So, in the future, if you want to change the layout file, you need to change the code in one place only, i.e., in the _ViewStart.cshtml file.

  • Automatic Execution: The _ViewStart.cshtml file is executed before rendering any view within the same directory or its subdirectories. This makes it an ideal place to set up common view settings.
  • Layout Specification: It is most commonly used to define a common layout page for various views. By specifying the layout in _ViewStart.cshtml, ensure that all views rendered by the application will use this layout unless explicitly overridden.
How to Create _ViewStart.cshtml file in ASP.NET Core MVC Application?

The _ViewStart.cshtml files are created within the Views or the Views folder’s subfolder. To create the _ViewStart.cshtml file, right-click on the Views folder and then select the Add – New Item option from the context menu; this will open the New Item window. From the New Item window, search for Razor and then select the Razor View Start template, provide the name as _ViewStart.cshtml, and click on the Add button as shown in the below image, which should create the _ViewStart.cshtml file within the Views folder of your project.

How to create _ViewStart.cshtml file in ASP.NET Core MVC Application?

If you are creating the ASP.NET Core Application using the Model-View-Controller Project template, then by default, the _ViewStart.cshtml file is added within the Views folder, as shown in the image below.

How to Create _ViewStart.cshtml file in ASP.NET Core MVC Application

Location and Scope: The placement of _ViewStart.cshtml within the application’s directory structure defines its scope. If placed in the root of the Views folder, its settings apply to all views. However, if you place it within a specific folder inside Views, it only affects views within that folder. You can have multiple _ViewStart.cshtml files at different levels of your application to apply different settings to different groups of views.

How to Set the Layout Property in ViewStart.cshtml file in ASP.NET Core MVC Application?

Once the ViewStart.cshtml file is created, then modify the file as shown below to set the Layout property. Here, you can see using the Layout property, and we are specifying the layout file path. So, use the Layout property to specify the path to your layout file. Layout files are typically in the Views/Shared folder and have the .cshtml file extension.

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Then, we need to remove the Layout property on individual views. So, modify the Index view of the Home Controller, i.e., the Index.cshtml View is inside the Views=>Home Folder, as shown below.

@{
    ViewBag.Title = "Home Page";
}

<h1>Home Page</h1>
@section Scripts {
    <script src="~/js/CustomJavascript.js"></script>
}

Next, modify the Details.cshtml view of Home Controller as follows.

@{
    ViewBag.Title = "Details Page";
}

<h1>Details Page</h1>

With the above changes in place, now run the application and navigate to Home/Index and Home/Details, and it should display the output as expected.

Understanding the Hierarchy of _ViewStart.cshtml File in ASP.NET Core MVC:

As we already discussed, we can place the _ViewStart file within the Views folder as well as its subfolder. So, we need to understand the hierarchical order of the ViewStart file. Let us understand this with an example.

The _ViewStart.cshtml file can be placed in the root of the Views directory or within any subdirectory under Views. ASP.NET Core MVC applications search for the _ViewStart.cshtml file using a top-down approach, starting from the specific view’s directory up to the root of the Views directory. This hierarchical search allows for fine-grained control over layout configurations at different levels of the application’s view structure.

  • Specific View Directory: If a _ViewStart.cshtml file is placed within the same directory (i.e., same folder) as a view, it will be applied to that view. This allows for specific layout settings to be defined for views within a particular folder.
  • Subdirectory Levels: If the view does not have a _ViewStart.cshtml file in its directory, the engine will search up the directory tree, looking into each parent directory for a _ViewStart.cshtml file. This feature is useful for setting common layout properties for a group of views under a specific subdirectory.
  • Root of the Views Directory: Ultimately, if no _ViewStart.cshtml file is found in any of the view’s parent directories, the engine will look for a _ViewStart.cshtml file in the root of the Views directory. This file, if present, acts as a default layout setter for all views across the application, unless overridden by a more specifically located _ViewStart.cshtml file.

Let us understand this with an example. First, create another layout file named _MyLayout.cshtml within the Shared folder. To do so, right-click on the Shared folder and then select Add => New Item from the context menu, which will open the following Add New Item window. Here, search for Layout and then select Razor Layout template, give the view name as _MyLayout.cshtml, and finally click on the Add button as shown below image, which should add _MyLayout.cshtml file within the Shared folder.

Understanding the hierarchy of _ViewStart.cshtml File in ASP.NET Core MVC

Once you create the _MyLayout.cshtml file, copy and paste the following code.

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        @RenderBody()
    </div>
    @if (IsSectionDefined("Scripts"))
    {
        @RenderSection("Scripts")
    }
</body>
</html>

With this Layout, we now have two layouts (_Layout.cshtml and _MyLayout.cshtml) for our application.

Creating Another ViewStart File within the Home Folder:

Let’s add another ViewStart file within the Home Folder, which is present within the Views folder. Once you create the ViewStart file, then modify the file as shown below. Here, we are setting the newly created _MyLayout.cshtml layout using the Layout property.

@{
    Layout = "~/Views/Shared/_MyLayout.cshtml";
}

With the above changes in place, the Views folder of your application should look as shown in the below image.

ViewStart in ASP.NET Core MVC

As you can see in the above image, we have placed one ViewStart file inside the Views folder and another ViewStart file inside the Home sub-folder. Now run the application and navigate to the Home/Index URL as shown in the below image.

ViewStart.cshtml file in ASP.NET Core MVC Application

The above Index view of the Home Controller uses MyLayout.cshtml view, which we specified within the _ViewStart.cshtml File, which is present inside the Home Folder. So, here, the Layout Page, specified in the _ViewStart.cshtml file in the Home sub-folder, overwrites the Layout Page, which is specified in the _ViewStart.cshtml File in the Views folder.

This means all the views that are present within the Views folder will use the layout page, which is specified in the _ViewStart.cshtml File in the Views folder, but the views in the Home folder will use the layout page specified in the _ViewStart.cshtml File in the Home folder.

How to Use a Different Layout Other the Layout Specified in the _ViewStart.cshtml File?

To use a different layout than the one specified in the _ViewStart.cshtml file in an ASP.NET MVC application, you can explicitly set the layout in your individual view files. The _ViewStart.cshtml file is used to define common site-wide settings, including the layout that is used by default for pages in your application. However, you can override these settings in specific views.

If you don’t want to use the layout file specified in the _ViewStart file either from the Home folder or the Views folder, you want to use a different layout file; then you need to use the Layout property in the individual view to set the layout. Let us understand this with an example. Create another Layout with the name _NewLayout.cshtml within the Shared Folder. Once you create the _NewLayout.cshtml file, copy and paste the following code.

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        <h4>This View Using _NewLayout.cshtml</h4>
        @RenderBody()
    </div>
</body>
</html>

I want to use the above _NewLayout.cshtml in the Details View of our Home Controller. To do so explicitly, we need to use the Layout property and provide the path of the _NewLayout.cshtml file. So, modify the Details.cshtml file as follows. 

@{
    ViewBag.Title = "Details Page";
    Layout = "~/Views/Shared/_NewLayout.cshtml";
}

<h1>Details Page</h1>

Now, run the application and navigate to Home/Details, and you should get the following output, which means the Details view is now using the Layout, which is specified in the Details view only.

How to Use a Diiferent Layout Other the Layout Specified in the _ViewStart.cshtml File

Now, if you don’t want to use any layout or want to render a view without a layout, then you need to set the Layout property to null. For example, if you don’t want to use a Layout in Details View, you need to modify the Details.cshtml view as follows.

@{
    ViewBag.Title = "Details Page";
    Layout = null;
}

<h1>Details Page</h1>

Now, run the application and navigate to the Home/Details URL, and you should see the output without using any layout page.

How Do We Select a Layout Conditionally in the ViewStart file?

To conditionally select a layout in the _ViewStart.cshtml file in an ASP.NET Core MVC application, you can use C# code to set the layout based on certain conditions. Here is a step-by-step guide on how to do this:

  • Identify the Condition: First, you need to determine the condition upon which you want to change the layout. This could be based on the current controller, action, user roles, or any custom logic.
  • Implement the Conditional Logic: Inside the _ViewStart.cshtml file, you can write C# code within @{ … } blocks. Use this capability to implement your conditional logic for selecting the layout.

When you work with a Real-Time ASP.NET Core MVC application, you may have multiple layout views. Let’s say you have two Layouts, such as _NonAdminLayout and _AdminLayout. If you want to select the layout based on the user role, i.e., if the user role is Admin, then use _AdminLayout; otherwise, use the _NonAdminLayout. Then, you need to write the following conditional logic within the _ViewStart.cshtml file, which will select the layout based on the logged-in user’s role.

@{
    if (User.IsInRole("Admin"))
    {
        Layout = "_AdminLayout";
    }
    else
    {
        Layout = "_NonAdminLayout";
    }
}

Here’s an example of how to select a layout based on the controller name. You can access route data through the ViewContext.RouteData property. The controller name is stored in this route data.

@{
    var controllerName = ViewContext.RouteData.Values["controller"].ToString();
    
    if (controllerName == "Home")
    {
        Layout = "~/Views/Shared/_HomeLayout.cshtml";
    }
    else if (controllerName == "Admin")
    {
        Layout = "~/Views/Shared/_AdminLayout.cshtml";
    }
    else
    {
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
}

In this example:

  • We first retrieve the name of the current controller.
  • Based on the controller’s name, we conditionally set the Layout property to different layout files.
When to Use _ViewStart.cshtml File in ASP.NET Core MVC?

The _ViewStart.cshtml file in ASP.NET Core MVC plays an important role in the application’s view rendering pipeline, serving as a common setup file that runs before rendering any view. Here’s when and why to use it:

To Apply Common Layout:

The primary use of _ViewStart.cshtml is to define a common layout file for the views in your application. This eliminates the need to specify the layout file in each view individually, promoting a DRY (Don’t Repeat Yourself) approach. You can set the layout for all views under a specific folder or the entire application by placing a _ViewStart.cshtml file in the respective directory.

Example:
@{
       Layout = “_Layout”;
}
This code snippet sets the _Layout.cshtml file as the default layout for all views located in the same directory as the _ViewStart.cshtml file or in subdirectories unless explicitly overridden in a specific view.

Setting Up Common ViewData or ViewBag Properties:

Though less common, _ViewStart.cshtml can be used to initialize ViewData or ViewBag properties that you want to be available in multiple views. For instance, setting a page title suffix that appears across several pages can be done here.

Example:
@{
      ViewData[“TitleSuffix”] = ” – My ASP.NET Core Application”;
}

Applying Common Settings or Conventions:

Apart from layouts and ViewData initialization, _ViewStart.cshtml can be utilized to apply any settings or conventions that should be common across multiple views. This could include setting up culture information, enforcing certain UI conventions, or initializing common UI components.

In the next article, I will discuss the _ViewImports.cshtml in ASP.NET Core MVC Application. Here, in this article, I try to explain the ViewStart in ASP.NET Core MVC Application.

Leave a Reply

Your email address will not be published. Required fields are marked *