在Razor Pages中的实现学生列表
admin
2022-01-10在Razor Pages中的实现学生列表
导航:
在此视频中,我们将实现 Razor代码以显示学生列表。我们希望列表 Razor Pages如下所示。
Index.cshtml.cs(PageModel)
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.RazorPages;
using YoYoMooc.StudentManagement.Models;
using YoYoMooc.StudentManagement.Services;
namespace YoYoMooc.StudentManagement.RazorPage.Pages.Students
{
public class IndexModel : PageModel
{
private readonly IStudentRepository _studentRepository;
/// <summary>
/// //这个公共属性保存学生列表 显示模板(Index.html)可以访问此属性
/// </summary>
public IEnumerable<Student> Students { get; set; }
/// <summary>
/// 注册IStudentRepository服务。通过这项服务知道如何查询学生列表
/// </summary>
/// <param name="studentRepository"></param>
public IndexModel(IStudentRepository studentRepository)
{
_studentRepository = studentRepository;
}
/// <summary>
/// 此方法处理发送GET请求 到路由 /Students/Index
/// </summary>
public void OnGet()
{
Students = _studentRepository.GetAllStudents();
}
}
}
Index.cshtml(视图文件)
@page
@model StudentManagement.RazorPage.Pages.Students.IndexModel
@{
ViewData["Title"] = "Index";
}
<style>
.btn {
width: 75px;
}
</style>
<h1>学生列表</h1>
<div class="card-deck">
@foreach (var student in Model.Students)
{
var photoPath = "~/images/" + (student.PhotoPath ?? "noimage.png");
<div class="card m-3" style="min-width: 18rem; max-width:30.5%;">
<div class="card-header">
<h3>@student.Name</h3>
</div>
<img class="card-img-top imageThumbnail" src="@photoPath"
asp-append-version="true" />
<div class="card-footer text-center">
<a href="#" class="btn btn-primary m-1">详情</a>
<a href="#" class="btn btn-primary m-1">编辑</a>
<a href="#" class="btn btn-danger m-1">删除</a>
</div>
</div>
}
</div>
site.css
.imageThumbnail {
height: 200px;
width: auto;
}
.card-body img{
height:350px;
width:auto;
}