添加测试页面
沿用之前的 MyWebApp 项目。
在 Controllers 文件夹下创建 HomeController:
using Microsoft.AspNetCore.Mvc;namespace MyWebApp.Controllers{public class HomeController : Controller{public IActionResult Home() => View();public IActionResult Page1() => View();public IActionResult Page2() => View();}}
接下来在 Views 文件夹下的 Home 文件夹里面创建 Home、Page1、Page2 页面:
Home.cshtml<h1>Home</h1><h2>Welcome to My Website</h2>Page1.cshtml<h1>Page1</h1><h2>Product List</h2>Page2.csthml@{ Layout = null; }<h1>Page2</h1><h2>Order List</h2>
创建 Layout 视图页
在 Views 文件夹下创建 Shared 文件夹,然后在该文件夹下创建 _Layout.cshtml:
<html><head><title>My Web App</title></head><body>|@Html.ActionLink("Home", "Home")|@Html.ActionLink("Page1", "Page1")|@Html.ActionLink("Page2", "Page2")|<hr/>@RenderBody()<hr/>Copyright | @DateTime.Now.ToString()</body></html>
为了将该 layout 页面应用到所有视图上,可以通过在 View 文件夹下创建 _ViewStart.cshtml,并添加如下代码:
@{ Layout = "_Layout"; }
运行程序并访问 http://localhost:5000/home/home。
可以看到 Home 和 Page1 中都应用了 Layout 视图
因为 Page2 使用
@{ Layout = null }重写了 _ViewStart 里面设置的 Layout 属性值,所以没有应用 Layout
