7 天玩转 ASP.NET MVC — 第 5 天(7233游戏盒)
7 天玩转 ASP.NET MVC — 第 5 天(7233游戏盒)
目录
0. 前言
欢迎来到第五天的学习。希望第一天到第四天的学习,你都是开心的。
1. Lab 22 — 增加 Footer
在这个实验中,我们将会向 Employee 页面添加 Footer。本次实验的目标是理解分部视图(Partial Views)。
什么是「Partial Views」?
第一步:为 Partial View 创建 ViewModel
右击 ViewModel 文件夹,然后创建一个类,命名为 FooterViewModel。
public class FooterViewModel { public string CompanyName { get; set; } public string Year { get; set; }}
第二步:创建 Partial View
右击「~/Views/Shared」文件夹,选择 Add -> View。
注意:我们已经在第一天的学习中谈论了 Shared 文件夹。Shared 文件夹包含了视图,这些视图不会属于一个特定的控制器。在 Shared 文件夹下的视图适用于所有控制器。
第三步:在 Partial View 中显示数据
打开 Footer.cshtml,然后放置如下代码。
@using WebApplication1.ViewModels@model FooterViewModel
第四步:在 Main ViewModel 中包含 Footer 数据
打开 EmployeeListViewModel 类,然后增加一个新的属性来承载 Footer 数据。
public class EmployeeListViewModel { public List
在我们的例子中,Footer 视图将会作为 Index 视图的一部分展示。
我们将会在 Index 视图中向 Footer 传输必要数据。
Index 视图是一个 EmployeeListViewModel 的强类型视图,因此 Footer 中需要的数据都应该被封装在 EmployeeListViewModel 类中。
第五步:设置 Footer 数据
打开 EmployeeController,然后在 Index 行为方法中设定 FooterData 属性值。
public ActionResult Index() { ... ... employeeListViewModel.FooterData = new FooterViewModel(); employeeListViewModel.FooterData.CompanyName = "StepByStepSchools";//Can be set to dynamic value employeeListViewModel.FooterData.Year = DateTime.Now.Year.ToString(); return View("Index", employeeListViewModel);}
第六步:展示 Footer
打开 Index.cshtml 文件,然后在 Table 标签后展示 Footer 视图。
@{ Html.RenderPartial("Footer", Model.FooterData); }