Here's the About.cshtml from the default MVC 3 template:
@{
ViewBag.Title = "About Us";
}
<h2>About</h2>
<p>
Put content here.
</p>
I would expect that a reference to the _ViewStart file would be found in the About.cshtml
, but clearly it's not.
I've looked in global.asax
and web.config
, but I can't find out how the About.cshtml
file is "linked" with the layout from the _ViewStart file.
Everything works as expected, I'd just like to know what's going on under the hood...
This may add some addt'l info to this question now (2016 ala MVC4, MVC5).
The Razor engine finds and runs the code in _ViewStart.cshtml before any other code which is in the same directory or subdirectory where the _ViewStart.cshtml is found.
Any view can override the Layout property or any of its values.
I too had same issue and later noticed that
app.UseStaticFiles();
were missing in pipe line.It is working after adding to pipeline.
If you want to have a common layout for your pages you need to define the common layout and to associate a view with layout we have to set layout property on each and every view, this violates the DRY(Don't Repeat Yourself) principle. For this .Net Framework has provide the "_ViewStart.cshtml" file, placed inside the view folder. We place layout information in "_ViewStart.cshtml" file and every view by default uses this layout information. If you want to give some different layout information, lets suppose to your Home view, you can create a new "_ViewStart.cshtml" with reference to that layout and place it in the "Home View" folder.
From ScottGu's blog:
Also see this.
Just another thought.
If you want to have your own
cshtml
file as a common template, you can do it this wayWithin your
_viewstart.cshtml
you can mention your commoncshtml
file.The source code is a much better place to look for this than the documentation.
Referencing the MVC 6 code from Github, we have a few files of interest
----update----
Due to source structure changes, the information on how viewstart pages are gathered can now be found in RazorViewEngine.cs look for "GetViewStartPages" function.
----/update----
To answer how they come into play, look at RazorView, Which I believe (because of IView) is tied in to the MVC pipeline. This file has a RenderAsync method that gets called from the MVC pipeline to render the requested view.
RenderAsync makes calls to RenderPage AND THEN RenderLayout (NOTE THE ORDER). The RenderPage first makes calls to deal with viewstart files (note plural, there could be more than one _viewstart file).
So, the information you seek can be obtained from RenderViewStartAsync function in RazorView.cs file under Microsoft.AspNet.Mvc.Razor namespace.