母版页
-
实现视图共享,需要修改的时候,只需要修改一句就行
-
一般在
/Views/Shared
目录下
在
/Views/Shared
目录下新建MyMasterPage.cshtml
文件
<html>
<head>
<title></title>
</head>
<body>
这是页面顶部内容 <br />
@* 使用RenderBody来显示页面内容 *@
@RenderBody()
<br />
这是页面底部内容
</body>
</html>
鼠标放在控制器的方法名上,右键
添加视图
选择视图模板:
@{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/MyMasterPage.cshtml";
}
<h2>Index</h2>
这是内容
- 内容隔离
子页面:
@{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/MyMasterPage.cshtml";
}
@section section1{
这是section1的内容
}
@section section2{
这是section2的内容
}
<h2>子页面主体</h2>
母版
<html>
<head>
<title></title>
</head>
<body>
这是页面顶部内容 <br />
@* 第二个参数表示分区是否是必须的 *@
@RenderSection("section1",false)
@RenderBody()
@RenderSection("section1")
<br />
这是页面底部内容
</body>
</html>
- 母版页数据绑定和普通数据绑定一致
Controller
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
[Controller]
public class Test : Controller
{
public IActionResult Index()
{
ViewBag.Username = "张三";
return View();
}
}
}
母版页:
<html>
<head>
<title></title>
</head>
<body>
这是页面顶部内容 <br />
@ViewBag.Username
@RenderBody()
<br />
这是页面底部内容
</body>
</html>
子页面
@{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/MyMasterPage.cshtml";
}
<h2>@ViewBag.Username</h2>
部分视图
- 直接引入部分视图
在
/Views/Shared
目录下新建一个MyPartPage.cshtml
的文件
<h2>这是部分共享视图</h2>
在
Index
视图里面引入
<html>
<head>
<title></title>
</head>
<body>
@Html.Partial("~/Views/Shared/MyPartPage.cshtml")
</body>
</html>
- 也可以直接在控制器里面返回部分视图,一般用于局部刷新(ajax)
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
[Controller]
public class Test : Controller
{
public IActionResult Index()
{
return PartialView("~/Views/Shared/MyPartPage.cshtml");
}
}
}
ViewStart
- 视图呈现之前执行
- 可以做全局性数据初始化,比如母版指定
- 以
_ViewStart.cshtml
命名,固定名称,不能更换 - 一般放在视图所在目录的根目录下
- 自动执行,无需手工调用
- 不要在
ViewStart
中做大量业务操作
ViewImports
- 以
_ViewImports.cshtml
命名,固定名称,不能更换 - 只能做引入操作
- 一般放在视图所在目录的根目录下
- 自动执行,无需手工调用