问题描述
这是来自默认 MVC 3 模板的 About.cshtml:
Here's the About.cshtml from the default MVC 3 template:
@{
ViewBag.Title = "About Us";
}
<h2>About</h2>
<p>
Put content here.
</p>
我希望可以在 About.cshtml
中找到对 _ViewStart 文件的引用,但显然不是.
I would expect that a reference to the _ViewStart file would be found in the About.cshtml
, but clearly it's not.
我查看了 global.asax
和 web.config
,但我无法找到 About.cshtml
文件与 _ViewStart 文件中的布局链接".
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...
推荐答案
来自 ScottGu 的博客:
从 ASP.NET MVC 3 Beta 版开始,您现在可以添加文件在下面称为 _ViewStart.cshtml(或 VB 的 _ViewStart.vbhtml)项目的 Views 文件夹:
_ViewStart 文件可用于定义您在希望在每个 View 渲染开始时执行.例如,我们可以在 _ViewStart.cshtml 文件中编写代码以以编程方式将每个 View 的 Layout 属性设置为默认为 SiteLayout.cshtml 文件:
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:
因为这段代码在每个View的开始执行,我们不再需要在我们的任何单独的视图文件中明确设置布局(除非我们想覆盖上面的默认值).
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).
重要:因为_ViewStart.cshtml 允许我们编写代码,我们可以选择性地使我们的布局选择逻辑更丰富,而不仅仅是一个基本属性集.例如:我们可以改变布局模板我们根据访问网站的设备类型使用 -并为这些设备优化了手机或平板电脑的布局,以及PC/笔记本电脑的桌面优化布局.或者如果我们正在构建一个跨多个客户使用的 CMS 系统或通用共享应用程序我们可以根据客户(或他们的角色)访问网站时.
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.
这实现了很多 UI 灵活性.它还可以让您更轻松编写一次视图逻辑,避免多次重复地方.
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.
另见这个.
这篇关于_ViewStart.cshtml 布局文件在哪里以及如何链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!