问题描述
我想显示我上传的特定产品的多张图片列表。但是当我使用循环显示时,我不明白为什么?这是我的代码:
型号
import mongoose from "mongoose";
const UserSchema = new mongoose.Schema({
uid: {
type: String,required: true,unique: true,},username: {
type: String,password: {
type: String,type: {
type: Number,createdAt: {
type: Date,default: Date.Now,});
module.exports = mongoose.model("UserSchema",UserSchema);
控制器
//model for multiple images
public class Photo1
{
[Key]
public int PhotoId { get; set; }
public string Image { get; set; }
}
//main model
public class Shop
{
public int Id { get; set; }
[required]
[display(Name = "product name")]
public String Name { get; set; }
[required]
public int Price { get; set; }
public String Image { get; set; }
public String Image1 { get; set; }
public List<Photo1> Photos { get; set; }
[required]
public int Quantity { get; set; }
[required]
public bool IsAvailable { get; set; }
[display(Name = "Category")]
public int? CategoryTypeId { get; set; }
[ForeignKey("CategoryTypeId")]
public Category Category { get; set; }
[display(Name = "SubCategory")]
public int? SubCategoryTypeId { get; set; }
[ForeignKey("SubCategoryTypeId")]
public SubCategory SubCategory { get; set; }
}
Details.cshtml
[HttpGet]
public ActionResult Details(int? id)
{
if (id == null)
{
return NotFound();
}
var product = _db.Shop.Include(c => c.Category).Include(c => c.SubCategory).FirstOrDefault(c => c.Id == id);
if (product == null)
{
return NotFound();
}
return View(product);
}
}
我的输出是:
解决方法
您应该循环浏览“照片”。 这就是错误所指示的内容。当您打算遍历照片时,它会尝试查找Shop(模型)的枚举数。
@if (Model.Photos != null)
{
@foreach (var photo in Model.Photos)
{
@if (photo.Image != null)
{
<img src="~/@photo.Image" alt="Card Image" class="card-img-top" style="height: 120px;"/>
}
}
}
您还应该在要退货的产品中包含照片,否则列表将为空。