.net _ViewStart.cshtml 布局文件在哪里以及如何链接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9300410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Where and how is the _ViewStart.cshtml layout file linked?
提问by Kman
Here's the About.cshtml from the default MVC 3 template:
这是来自默认 MVC 3 模板的 About.cshtml:
@{
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.
我希望在 中可以找到对 _ViewStart 文件的引用About.cshtml,但显然不是。
I've looked in global.asaxand web.config, but I can't find out how the About.cshtmlfile is "linked" with the layout from the _ViewStart file.
我查看了global.asax和web.config,但我无法About.cshtml从 _ViewStart 文件中找出该文件是如何与布局“链接”的。
Everything works as expected, I'd just like to know what's going on under the hood...
一切都按预期工作,我只想知道引擎盖下发生了什么......
回答by jim tollan
From ScottGu's blog:
来自ScottGu 的博客:
Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:
The _ViewStart file can be used to define common view code that you want to execute at the start of each View's rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:
Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).
Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.
This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.
从 ASP.NET MVC 3 Beta 版本开始,您现在可以在项目的 \Views 文件夹下添加一个名为 _ViewStart.cshtml(或 VB 的 _ViewStart.vbhtml)的文件:
_ViewStart 文件可用于定义要在每个视图渲染开始时执行的公共视图代码。例如,我们可以在 _ViewStart.cshtml 文件中编写代码,以编程方式将每个视图的 Layout 属性设置为默认的 SiteLayout.cshtml 文件:
因为这段代码在每个视图的开始执行,我们不再需要在任何单独的视图文件中显式设置布局(除非我们想覆盖上面的默认值)。
重要提示:因为 _ViewStart.cshtml 允许我们编写代码,所以我们可以选择性地使我们的布局选择逻辑更丰富,而不仅仅是基本的属性集。例如:我们可以根据访问网站的设备类型来改变我们使用的布局模板——并为这些设备提供手机或平板电脑优化的布局,以及为个人电脑/笔记本电脑优化的桌面布局。或者,如果我们正在构建一个跨多个客户使用的 CMS 系统或通用共享应用程序,我们可以在访问站点时根据客户(或他们的角色)选择不同的布局来使用。
这实现了很多 UI 灵活性。它还允许您更轻松地编写一次视图逻辑,并避免在多个地方重复。
Also see this.
也看到这个。
回答by rism
In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".
在更一般的意义上,MVC 框架“了解”_Viewstart.cshtml 的这种能力称为“按约定编码”。
Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.
约定优于配置(也称为约定编码)是一种软件设计范式,旨在减少开发人员需要做出的决策数量,获得简单性,但不一定会失去灵活性。该短语本质上意味着开发人员只需要指定应用程序的非常规方面。例如,如果模型中有一个类Sale,则数据库中对应的表默认称为“sales”。只有在偏离这一约定时,例如将表称为“products_sold”,才需要编写有关这些名称的代码。
Wikipedia
维基百科
There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.
它没有魔法。它刚刚被写入MVC框架的核心代码库,因此是MVC“知道”的东西。这就是为什么您在 .config 文件或其他地方找不到它的原因;它实际上在 MVC 代码中。但是,您可以覆盖以更改或取消这些约定。
回答by user2515392
Just another thought.
只是另一个想法。
If you want to have your own cshtmlfile as a common template, you can do it this way
如果你想拥有自己的cshtml文件作为通用模板,你可以这样做
Within your _viewstart.cshtmlyou can mention your common cshtmlfile.
_viewstart.cshtml您可以在您的公共cshtml文件中提及。
@{Layout = "~/Views/Shared/_Layout.cshtml";}
回答by Frison Alexander
The source code is a much better place to look for this than the documentation.
源代码是一个比文档更好的地方。
Referencing the MVC 6 codefrom Github, we have a few files of interest
引用来自 Github的MVC 6 代码,我们有一些感兴趣的文件
----update----
- - 更新 - -
Due to source structure changes, the information on how viewstart pages are gathered can now be found in RazorViewEngine.cslook for "GetViewStartPages" function.
由于源结构更改,现在可以在RazorViewEngine.cs查找“GetViewStartPages”函数中找到有关如何收集 viewstart 页面的信息。
----/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.
要回答它们如何发挥作用,请查看RazorView,我认为(因为 IView)与 MVC 管道相关联。此文件有一个 RenderAsync 方法,该方法从 MVC 管道中调用以呈现请求的视图。
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).
RenderAsync 调用 RenderPage 然后调用 RenderLayout(注意顺序)。RenderPage 首先调用处理 viewstart 文件(注意复数,可能有多个 _viewstart 文件)。
So, the information you seek can be obtained from RenderViewStartAsync function in RazorView.csfile under Microsoft.AspNet.Mvc.Razor namespace.
因此,您可以从Microsoft.AspNet.Mvc.Razor 命名空间下的RazorView.cs文件中的RenderViewStartAsync 函数中获取您要查找的信息。
回答by raddevus
This may add some addt'l info to this question now (2016 ala MVC4, MVC5).
这现在可能会为这个问题添加一些附加信息(2016 ala MVC4,MVC5)。
The Razor engine finds and runs the code in _ViewStart.cshtmlbefore any other code which is in the same directory or subdirectory where the _ViewStart.cshtmlis found.
剃刀引擎查找和运行在代码_ViewStart.cshtml之前的任何其他代码其是在所述相同的目录或子目录_ViewStart.cshtml被发现。
Any view can override the Layoutproperty or any of its values.
任何视图都可以覆盖Layout属性或其任何值。
Just thought I might add a bit more info to show you why it is _ViewStart.
只是想我可能会添加更多信息来向您展示为什么它是 _ViewStart。
If you get ILSpyand examine the code in the RazorViewEngine (System.Web.Mvc.dll ) you will see that the code itself references that name.
如果您获得ILSpy并检查 RazorViewEngine (System.Web.Mvc.dll) 中的代码,您将看到代码本身引用了该名称。


You can see that the RazorViewEngine looks for a file with that name:
您可以看到 RazorViewEngine 查找具有该名称的文件:
RazorViewEngine.ViewStartFileName = "_ViewStart";
回答by KamalDeep
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.
如果你想为你的页面有一个通用的布局,你需要定义通用布局并将视图与布局相关联,我们必须在每个视图上设置布局属性,这违反了 DRY(不要重复自己)原则。为此 .Net Framework 提供了“_ViewStart.cshtml”文件,放置在视图文件夹中。我们将布局信息放在“_ViewStart.cshtml”文件中,默认情况下每个视图都使用此布局信息。如果您想提供一些不同的布局信息,假设您的主页视图,您可以参考该布局创建一个新的“_ViewStart.cshtml”并将其放置在“主页视图”文件夹中。
回答by Shadi Namrouti
The short answer is: ViewStarts start first when any view is being rendered. The long story is below:
简短的回答是:当任何视图被渲染时,ViewStarts 首先启动。长故事如下:
The story of the creation of a single view file:
创建单个视图文件的故事:
- The ViewStart is merged with ViewImports and then executed as a single file. Note that ViewImports is always merged with any cshtml file including the ViewStart file. Its purpose is to abstract @using statements and other common directives.
- The output of ViewStart (such as Layout and ViewData) becomes available to the specific View file.
- Inside the View file, if the Layout variable is/becomes null, the body of the view is rendered and the final output is delivered to the user.
- If the Layout variable is/becomes not null, the execution is moved to the layout file which in turn is merged with ViewImports as a single file and then at the @RenderBody() statement inside the layout file execution is moved back to the view file which is merges with ViewImports again and the output is merged with the layout file at the location of @RenderBody() and the final output is finally delivered to the user.
- ViewStart 与 ViewImports 合并,然后作为单个文件执行。请注意,ViewImports 始终与任何 cshtml 文件(包括 ViewStart 文件)合并。它的目的是抽象@using 语句和其他常用指令。
- ViewStart 的输出(例如 Layout 和 ViewData)可用于特定的 View 文件。
- 在 View 文件中,如果 Layout 变量为/变为 null,则呈现视图的主体并将最终输出交付给用户。
- 如果 Layout 变量是/变得不为 null,则执行将移至布局文件,该文件又与 ViewImports 合并为单个文件,然后在布局文件中的 @RenderBody() 语句处将执行移回视图文件它再次与 ViewImports 合并,输出与 @RenderBody() 位置的布局文件合并,最终输出最终交付给用户。
Hopes this makes you aware of what's really going on inside the unknown mysteries of your program's life cycle.
希望这能让您了解程序生命周期的未知奥秘中到底发生了什么。

