ViewStart in ASP.NET Core MVC

ViewStart in ASP.NET Core MVC Application

In this article, I am going to 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. Our previous article discussed the Sections in Layout View in ASP.NET Core MVC Application. As part of this article, we are going to 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 Application?
  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.
  6. How to Select a Layout Conditionally in the ViewStart file?
Why Do We Need _ViewStart.cshtml File in ASP.NET Core MVC Application?

In ASP.NET Core MVC, the _ViewStart.cshtml file is a special Razor view file. It allows us to define the layout and other settings that will be applied to multiple views within a specific directory and its subdirectories. It provides a way to establish a consistent layout, apply common settings, and reduce repetitive code in your views.

It helps us to centralize common configurations or settings and avoid duplicating code across multiple views. The ViewStart file is automatically executed before rendering any views in its directory hierarchy.

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 the following 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 of the views. To solve the above problems, we need to use the _ViewStart.cshtml file.

What is _ViewStart.cshtml file in ASP.NET Core MVC Application?

In ASP.NET Core MVC Application, the _ViewStart.cshtml file is a special file, and the code present in this file is going to be executed before the code in an individual view is executed. So, you can set the Layout Property in this file as shown in the below image 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, then maintaining the application becomes much easier. So, in the future, if you want to change the layout file, then you need to change the code in one place only, i.e., in the _ViewStart.cshtml file.

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 below image.

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

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.

@{
    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 present inside the View=>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.

First, Let us 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 _Layout.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, then 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, which is 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 which 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 present 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?

If you don’t want to use the layout file which is specified in the _ViewStart file either from the Home folder or from the Views folder, rather you want to use a different layout file, then you need to use the Layout property in 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 need to 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 navigates to Home/Details, and you should get the following output, which means now the Details view is 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 if you 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, then 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 to Select a Layout conditionally in the ViewStart file?

When you work with a Real-Time ASP.NET Core MVC application, then 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 else, use the _NonAdminLayout. Then it would be best if you wrote the following 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";
    }
}
Key Points of ViewStart in ASP.NET Core MVC

Layout Definition: One of the primary purposes of _ViewStart.cshtml is to define the layout that will be used for views in the same directory and its subdirectories. This helps ensure consistent structure, styling, and UI elements across multiple views. Example of defining a layout in _ViewStart.cshtml:

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

In this example, the layout for views in the current directory and its subdirectories is set to _Layout.cshtml located in the Views/Shared directory.

Common Settings: You can use _ViewStart.cshtml to define other common settings that should be applied to all views in the directory and its subdirectories. This can include things like default view data, HTML helpers, and other Razor code. Example of setting default view data in _ViewStart.cshtml:

@{
    ViewData["CommonValue"] = "This is a common value for all views";
}

By using _ViewStart.cshtml, you can establish a consistent layout, share common settings, and simplify the process of rendering views throughout your ASP.NET Core MVC application. It helps you avoid duplicating layout and setting code across multiple views and enhances the maintainability and readability of your codebase.

In the next article, I am going to 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 *