ASP.NET Core - Razor View Start


Advertisements

In this chapter, we will discuss the Razor View Start. The Razor view engine in MVC has a convention where it will look for any file with the name _ViewStart.cshtml and execute the code inside this file. before executing the code inside an individual view.

ViewStart Cshtml
  • The code inside the ViewStart file cannot render into the HTML output of a page, but it can be used to remove duplicate code from the code blocks inside the individual views.

  • In our example, if we want every view to use the Layout view that we have created in the last chapter, we could put the code to set the Layout view inside a ViewStart instead of having the code inside every view.

Example

Let us take a simple example to see how this works. In our application, we don't want every view to specify that its Layout view is _Layout.cshtml. So right-click on the Views folder and select Add → New Item.

Layout Cshtml Add New Item

There is a specific template in ASP.NET MVC for a ViewStart page, so select MVC View Start Page in the middle pane. The most important part here is that this file is named _ViewStart.cshtml. Now click on the Add button.

View Cshtml

The primary use of a ViewStart file is to set the Layout view.

Let us now go to the Index.cshtml file and cut the Layout line and then add it to the ViewStart file as shown in the following program.

@{ 
   Layout = "~/Views/Shared/_Layout.cshtml"; 
}
  • When the MVC framework goes to render a view, it will see if there Is a ViewStart file somewhere in the folder hierarchy.

  • We have placed _ViewStart directly into our Views folder. This is going to impact all the views in all the folders that are inside the Views folder, and both the views inside the Home folder, as well as the Shared folder, as well as any other controller folders that we might add in the future.

  • If we take ViewStart and place it only in the Home folder, then this little bit of code would only execute when we are rendering one of those views in the Home folder.

  • We can even have multiple ViewStart files, so we could have a ViewStart.cshtml here in the Views folder that sets the Layout view for all views.

  • But if we wanted to change that default for all of the views just in the Home folder, we could have another ViewStart in the Home folder that sets the layout to something else.

Let us save all the files and run the application.

ViewStart File

You will see that your home page still renders just the way it did before, and we still have the Layout view in effect.

Advertisements