编辑年级

添加Get和Update方法

在GradeService中添加Get方法和Update方法,代码如下:

public GradeViewModel Get(Guid id)
{
    Grade? grade = gradeRepo.Get(id);
    if (grade == null)
    {
        throw new NullReferenceException();
    }

    GradeViewModel model = new GradeViewModel()
    {
        Id = grade.Id,
        Name = grade.Name,
    };
    return model;
}

public void Update(GradeViewModel model)
{
    Grade grade = new Grade()
    {
        Id = model.Id,
        Name = model.Name,
    };
    gradeRepo.Update(grade);
}

添加Edit动作

在GradeController中添加2个Edit动作,代码如下:

public IActionResult Edit(Guid id)
{
    GradeViewModel model;
    try
    {
        model = gradeService.Get(id);
    }
    catch (NullReferenceException)
    {
        return NotFound();
    }
    return View(model);
}

[HttpPost]
public IActionResult Edit(GradeViewModel model)
{
    if (ModelState.IsValid)
    {
        gradeService.Update(model);
        return RedirectToAction("Index");
    }
    return View(model);
}

添加Edit视图

在Grade视图模块下创建Edit.cshtml视图文件,代码如下:

@{
    ViewBag.Title = "编辑专业";
}
@model GradeViewModel

<form method="post" class="mx-auto" style="width:320px;">
    <div asp-validation-summary="All" class="has-text-danger mb-4"></div>
    <input asp-for="Id" hidden>
    <div class="field">
        <label asp-for="Name" class="label"></label>
        <div class="control">
            <input asp-for="Name" class="input">
        </div>
    </div>
    <div class="field">
        <button class="button is-primary is-fullwidth">提交</button>
    </div>
</form>