ASP.NET CORE Mvc – _ViewStart.cshtml
In this tutorial we will discuss view start in a ASP.NET Core MVC. How apply layout to all views and apply multiple layouts.
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 instead of setting the Layout Property in each individual view which is going to be executed before the actual view is executed.
Let’s take an example, As of now we have assigned a layout page for a particular view but suppose we have 50 views in our application and all the 50 views want to use the same layout file. Then we need to set the Layout Property on each view and suppose in future if we want to apply a different layout then we need to change in all 50 views. This process is tedious, time-consuming as well as error-prone because you may miss updating the Property in some of the views. To overcome these problems we need to make use the _ViewStart.cshtml file. In MVC, the _ViewStart.cshtml files are created within the Views or within the subfolder of the Views folder. To create “_ViewStart.cshtml” file right click on the Views folder and then select “Add – New Item” option from the context menu, this will opens the “New Item” window. From the “New Item” window search for “Razor” and then select the “Razor View Start” and click on the “Add” which should create the “_ViewStart.cshtml” within the “Views” folder.Now lets modify ViewStart.cshtml file and see how to set layout. We need use layout property to set layout and we need to remove the Layout property on individual views. So, modify StudentDetails view.
@{ Layout = "~/Views/Shared/_Layout.cshtml"; }
So now suppose you want apply multiple layout and so the question comes to our mind: can we add multiple view-start files? The answer is yes we can add multiple view start file.
So lets add another layout page first into shared folder and another view start file inside the sub folder you need to hierarchical working on viewstart. Once we create the ViewStart file then modify the file. Here, we are setting the newly created _HomeLayout.cshtml in the Layout property.
The Index view uses HomeLayout.cshtml view which we specified within the ViewStart File which is present inside the Home Folder. So, here the layout page which is specified in the ViewStart file in the Home sub-folder overwrites the layout page specified in the ViewStart 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 file in the Views folder, but the views which are present in the Home folder will use the layout page which is specified in the ViewStart file in the Home folder.
You can watch our video version of this tutorial with step by step explanation.