当 Student 领域模型不满足我们的需求时,我们引入用于创建 Student 的 StudentCreateViewModel。

    上传图片的 input 控件:

    1. <div class="form-group row">
    2. <label asp-for="Photo" class="col-sm-2 col-form-label"></label>
    3. <div class="col-sm-10">
    4. <div class="custom-file">
    5. <input asp-for="Photo" class="form-control custom-file-input" />
    6. <label class="custom-file-label">请选择照片...</label>
    7. </div>
    8. </div>
    9. </div>

    后台处理图片上传:

    1. [HttpPost]
    2. public IActionResult Create(StudentCreateViewModel model)
    3. {
    4. if (ModelState.IsValid)
    5. {
    6. string uniqueFileName = null;
    7. if (model.Photo != null)
    8. {
    9. var uploadFolder = Path.Combine(_hostingEnvironment.WebRootPath, "images");
    10. uniqueFileName = Guid.NewGuid() + "_" + model.Photo.FileName;
    11. var filePath = Path.Combine(uploadFolder, uniqueFileName);
    12. model.Photo.CopyTo(new FileStream(filePath, FileMode.Create));
    13. }
    14. var student = new Student
    15. {
    16. Name = model.Name,
    17. Email = model.Email,
    18. ClassName = model.ClassName,
    19. PhotoPath = uniqueFileName
    20. };
    21. var newStudent = _studentRepository.Add(student);
    22. return RedirectToAction("Details", new { id = newStudent.Id });
    23. }
    24. return View();
    25. }

    解析图片路径,展示图片:

    1. <div class="card-deck">
    2. @foreach (var student in Model)
    3. {
    4. var photoPath = $"~/images/{student.PhotoPath ?? "noimage.jpg"}";
    5. <div class="card m-3">
    6. <div class="card-header">
    7. <h3>@student.Name</h3>
    8. </div>
    9. <img class="card-img-top imagesThumbnail" src="@photoPath" asp-append-version="true" />
    10. <div class="card-footer text-center">
    11. <a asp-controller="home" asp-action="details" asp-route-id="@student.Id" class="btn btn-primary m-1">查看</a>
    12. <a href="#" class="btn btn-primary m-1">编辑</a>
    13. <a href="#" class="btn btn-danger m-1">删除</a>
    14. </div>
    15. </div>
    16. }
    17. </div>