MVC 中的视图

关于MVC视图的呈现

MVC 中视图的类型

_Layout.cshtml

位于 View 文件夹下的 Shared 文件夹中, Layout.cshtml 文件的内容通常是在所有页面都需要出现的内容,这个文件被称为 视图的布局页 ,也可以理解为 母版页 的概念。文件中会有一条 RenderBody() 语句,用来将普通视图页载入到当前位置,一个项目不一定具有布局页,也不一定只具有一个布局页

_ViewStart.cshtml

位于 View 文件夹根目录,顾名思义: ViewStart.cshtml 文件是视图的启动文件,这个页面可以用来引入一些所有页面都需要的资源(比如:引入jQuery),或者进行一些所有页面都需要的设置(比如:设置布局页)

Index.cshtml

普通视图,位于 View 文件夹下的和控制器同名的文件夹中,一般每个视图都有对应的动作。可以直接右键在浏览器中查看

_ListPartial.cshtml

分部视图,和普通视图位于同一个文件夹中,但是命名规则同 Layout.cshtmlViewStart.cshtml (以下划线开头),通常在普通视图中通过 Html.Partial() 语句载入,不能单独在浏览器中查看

MVC 中视图的加载顺序

具有布局页

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.
├── 访问一个路由,例如:localhost:80/Home/Index
├── 读取 _ViewStart.cshtml 设置的布局页
├── 读取 Index.cshtml 设置的布局页
├── 需要使用布局页(假定需要载入名为 Layout 的布局页)
├── 开始载入 _Layout.cshtml 页
| ├── 检测到 RenderBody() 语句,暂停载入 _Layout.cshtml 页
| ├── 开始载入 _ViewStart.cshtml 页,_ViewStart.cshtml 页载入完毕
| ├── 开始载入 Index.cshtml 页
| | ├── 检测到 Html.Partial("_ListPartial") 语句,暂停载入 Index.cshtml 页
| | └── 开始载入 _ListPartial.cshtml 页, _ListPartial.cshtml 页载入完毕
| └── 继续载入 Index.cshtml 页,Index.cshtml 页载入完毕
├── 继续载入 _Layout.cshtml 页, _Layout.cshtml 页载入完毕
└── 呈现页面

不具有布局页

1
2
3
4
5
6
7
8
9
10
11
.
├── 访问一个路由,例如:localhost:80/Home/Index
├── 读取 _ViewStart.cshtml 设置的布局页
├── 读取 Index.cshtml 设置的布局页
├── 不需要使用布局页
├── 开始载入 _ViewStart.cshtml 页,_ViewStart.cshtml 页载入完毕
├── 开始载入 Index.cshtml 页
| ├── 检测到 Html.Partial("_ListPartial") 语句,暂停载入 Index.cshtml 页
| └── 开始载入 _ListPartial.cshtml 页, _ListPartial.cshtml 页载入完毕
├── 继续载入 Index.cshtml 页,Index.cshtml 页载入完毕
└── 呈现页面

关于应用布局页的争执

ViewStart.cshtml 和普通视图中都存在 Layout 设置时,以普通视图的设置为准
ViewStart.cshtml 中存在 Layout 设置,普通视图中不存在 Layout 设置时,以 ViewStart.cshtml 的设置为准
ViewStart.cshtml 和普通视图中都不存在 Layout 设置时,不具有布局页

_ViewStart.cshtml Index.cshtml 实际应用
Layout = “…/_Layout.cshtml” Layout = “…/_Layout.cshtml” Layout = “…/_Layout.cshtml”
Layout = “…/_LayoutA.cshtml” Layout = “…/_LayoutB.cshtml” Layout = “…/_LayoutB.cshtml”
Layout = “…/_Layout.cshtml” Layout = “” Layout = “…/_Layout.cshtml”
Layout = “…/_Layout.cshtml” Layout = null Layout = null
Layout = “” Layout = “…/_Layout.cshtml” Layout = “…/_Layout.cshtml”
Layout = “” Layout = “” Layout = “”
Layout = null Layout = null Layout = null