Hi All, if you are new to MVC, read my earlier blogs on MVC. In my previous blog, I wrote about MVC routing. In this article, we will see the What is _ViewStart.cshtml file?
What is ViewStart.cshtml file?
_ViewStart.cshtml file is used to define the common layout page for all the views you add to your project. If you add a view, you see below dialog box to provide the View name, View Engine and Layout or master page.
If you have used _viewstart.cshtml file then no need to define Layout or Master page, leave that field blank as you can see in above screenshot.
So what _viewstart.cshtml file contains?
_viewstart.cshtml file contains below line of code. It contains the Layout view location as shown below.
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
Benefits of _viewstart.cshtml file in MVC
Suppose I have more than 100 views in my project, in this condition –
Benefit #1 – No need to provide Layout name in each and every view. Just add in _viewstart.cshtml file and it works for all views.
Benefit #2 – In future suppose you plan to change the view name, now think how much time it will take to rename Layout page in 100 of Views available in the project. Too hard? right? Now _viewstart.cshtml file will make your life easier, just change at one place and it is done.
How to add _ViewStart file in MVC?
To Add _ViewStart.cshtml file, right-click on Views folder and select Add then View. In the dialog box, please type _ViewStart (as shown in below screenshot). Remember _ViewStart is important.
Can we have more than one _ViewStart.cshtml file in Views folder?
Answer – No, You can have only one _viewstart.cshtml file in a Views folder.
Instead of providing _Layout.cshtml path, what will happen if we pass null.?
@{
Layout = null;
}
Answer – There will be no error on the page, instead it will load without Layout file i.e. if you have defined css, script path in Layout then those files will not load.
Takeaway –
In this article, we learn what is viewstart.cshtml file and what are the benefits of using viewstart.cshtml in MVC project.
- Anti-forgery tokens in MVC
- Data Annotation in MVC
- What is ViewModel?
- How to Pass data from Controller to View?