在GradeService中添加GetList方法,代码如下:
public List<GradeViewModel> GetList()
{
List<Grade> grades = gradeRepo.GetList();
List<GradeViewModel> gradeViewModels = new List<GradeViewModel>();
foreach (var grade in grades)
{
gradeViewModels.Add(new GradeViewModel()
{
Id = grade.Id,
Name = grade.Name,
});
}
return gradeViewModels;
}
在GradeController的Index动作中通过GradeService的GetList获取视图模型数据,并返回给视图,代码如下:
public IActionResult Index()
{
return View(gradeService.GetList());
}
在Grade视图模块下创建Index.cshtml文件,代码如下:
@{
ViewBag.Title = "年级管理";
}
@model List<GradeViewModel>
<div>
<a asp-action="Add" class="button is-primary mb-4">添加年级</a>
<table class="table is-bordered is-striped is-hoverable is-fullwidth">
<thead>
<tr>
<th>年级</th>
<th>操作</th>
</tr>
</thead>
<tbody>
@foreach (var grade in Model)
{
<tr>
<td>@grade.Name</td>
<td>
<a asp-action="Edit" asp-route-id="@grade.Id" class="button is-warning">编辑</a>
</td>
</tr>
}
</tbody>
</table>
</div>
这里直接将编辑按钮添加进来,为后续做准备。