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 blog, we will see the 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
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?
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.
Note: You can have only one _viewstart.cshtml file in a Views folder.
Interview Question – 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 having items defined in Layout.cshtml i.e. if you have defined css, script path in Layout then these files will not load.
- Anti-forgery tokens in MVC
- Data Annotation in MVC
- What is ViewModel?
- How to Pass data from Controller to View?
Please follow and like us: