创建详细信息页
学生 Index
的 "基架" 代码页遗留了 Enrollments
属性,因为该属性包含一个集合。 在 "Details
" 页中,将在 HTML 表中显示集合的内容。
在 Controllers\StudentController.cs 中,Details
视图的操作方法使用Find方法检索单个 Student
实体。
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Student student = db.Students.Find(id);
if (student == null)
{
return HttpNotFound();
}
return View(student);
}
键值作为 id
参数传递给方法,并来自索引页上 详细信息 超链接中的 路由数据。
提示:路由数据
路由数据是模型绑定器在路由表中指定的 URL 段中找到的数据。 例如,默认路由指定 controller
、action
和 id
段:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
在下面的 URL 中,默认路由映射 Instructor
作为 controller
,Index
作为 action
,1作为 id
;这些是路由数据值。
http://localhost:1230/Instructor/Index/1?courseID=2021
?courseID=2021
是一个查询字符串值。 如果将 id
作为查询字符串值传递,则模型绑定器也起作用:
http://localhost:1230/Instructor/Index?id=1&CourseID=2021
Url 是通过 Razor 视图中 ActionLink
语句创建的。 在下面的代码中,id
参数与默认路由匹配,因此 id
添加到路由数据。
@Html.ActionLink("Select", "Index", new { id = item.PersonID })
在下面的代码中,courseID
与默认路由中的参数不匹配,因此将其添加为查询字符串。
@Html.ActionLink("Select", "Index", new { courseID = item.CourseID })
创建详细信息页
-
打开 Views\Student\Details.cshtml。
每个字段都使用
DisplayFor
帮助器来显示,如以下示例中所示:<dt> @Html.DisplayNameFor(model => model.LastName) </dt> <dd> @Html.DisplayFor(model => model.LastName) </dd>
-
在 "
EnrollmentDate
" 字段之后,在 "结束</dl>
标记之前,添加突出显示的代码以显示注册列表,如以下示例中所示:<dt> @Html.DisplayNameFor(model => model.EnrollmentDate) </dt> <dd> @Html.DisplayFor(model => model.EnrollmentDate) </dd> <dt> @Html.DisplayNameFor(model => model.Enrollments) </dt> <dd> <table class="table"> <tr> <th>Course Title</th> <th>Grade</th> </tr> @foreach (var item in Model.Enrollments) { <tr> <td> @Html.DisplayFor(modelItem => item.Course.Title) </td> <td> @Html.DisplayFor(modelItem => item.Grade) </td> </tr> } </table> </dd> </dl> </div> <p> @Html.ActionLink("Edit", "Edit", new { id = Model.ID }) | @Html.ActionLink("Back to List", "Index") </p>
如果代码缩进在粘贴代码后出现错误,请按 ctrl+K, ctrl+D 对其进行格式化。
此代码循环通过
Enrollments
导航属性中的实体。 对于属性中的每个Enrollment
实体,它显示课程标题和分数。 课程标题将从存储在Enrollments
实体的Course
导航属性中的Course
实体中进行检索。 在需要时,将自动从数据库中检索所有数据。 换句话说,你在此处使用延迟加载。 你没有为Courses
导航属性指定 预先加载,因此无法在获得学生的同一查询中检索注册。 相反,第一次尝试访问Enrollments
导航属性时,会将新查询发送到数据库以检索数据。 可以在本系列后面的读取相关数据教程中详细了解延迟加载和预先加载。 -
通过启动程序(Ctrl+