当 Student 领域模型不满足我们的需求时,我们引入用于创建 Student 的 StudentCreateViewModel。
上传图片的 input 控件:
<div class="form-group row">
<label asp-for="Photo" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<div class="custom-file">
<input asp-for="Photo" class="form-control custom-file-input" />
<label class="custom-file-label">请选择照片...</label>
</div>
</div>
</div>
后台处理图片上传:
[HttpPost]
public IActionResult Create(StudentCreateViewModel model)
{
if (ModelState.IsValid)
{
string uniqueFileName = null;
if (model.Photo != null)
{
var uploadFolder = Path.Combine(_hostingEnvironment.WebRootPath, "images");
uniqueFileName = Guid.NewGuid() + "_" + model.Photo.FileName;
var filePath = Path.Combine(uploadFolder, uniqueFileName);
model.Photo.CopyTo(new FileStream(filePath, FileMode.Create));
}
var student = new Student
{
Name = model.Name,
Email = model.Email,
ClassName = model.ClassName,
PhotoPath = uniqueFileName
};
var newStudent = _studentRepository.Add(student);
return RedirectToAction("Details", new { id = newStudent.Id });
}
return View();
}
解析图片路径,展示图片:
<div class="card-deck">
@foreach (var student in Model)
{
var photoPath = $"~/images/{student.PhotoPath ?? "noimage.jpg"}";
<div class="card m-3">
<div class="card-header">
<h3>@student.Name</h3>
</div>
<img class="card-img-top imagesThumbnail" src="@photoPath" asp-append-version="true" />
<div class="card-footer text-center">
<a asp-controller="home" asp-action="details" asp-route-id="@student.Id" 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>