使用视图模型从数据库显示多个图像

时间:2017-02-16 00:20:56

标签: asp.net asp.net-mvc database

我想在我的视图中显示多个图像。所以我上传图像到文件系统和有关图像存储在数据库中的信息。我有一对多的表关系("scripts": { "preinstall": "cross-var echo ${npm_package_name}" } 是主表,Furniture我保存图像的信息)。我也使用View模型。

但是图像不希望显示,因为在编辑GET方法中传递参数FurnitureImages有问题。我无法写List<SecondaryImages>,因为它是model.SecondaryImages. = ...这是我的代码部分。

控制器

List

数据模型

public ActionResult Edit(int? id)
{
    ....
    var furniture = db.Furnitures.Find(id);
    FurnitureVM model = new FurnitureVM();
    model.Name = furniture.Name;
    .... // set other properties of the view model based on the data model
    FurnitureImages main = furniture.Images.Where(x => x.IsMainImage).FirstOrDefault();
    foreach(var i in model.SecondaryImages)
    {
        i.DisplayName = main.DisplayName;
        i.Path = main.Path;
        i.IsMainImage = main.IsMainImage;
    }
    return View(model);
}

查看模型

public class Furniture
{
    ....
    public virtual ICollection<FurnitureImages> Images { get; set; }
}
public class FurnitureImages
{
    [Key]
    public int Id { get; set; }
    public string Path { get; set; }
    public string DisplayName { get; set; }
    public bool IsMainImage { get; set; } // this determines if its the main or secondary image
    public int FurnitureId { get; set; } // navigation property
    public virtual Furniture Furniture { get; set; }
}

查看

public class FurnitureVM
{
    public FurnitureVM()
    {
        ....
        this.SecondaryImages = new List<ImageVM>();
    }       
    ....
    public IEnumerable<HttpPostedFileBase> SecondaryFiles { get; set; }
    public List<ImageVM> SecondaryImages { get; set; }        
}
public class ImageVM
{ 
    public int? Id { get; set; }
    public string Path { get; set; }
    public string DisplayName { get; set; }
    public bool IsMainImage { get; set; }
}

1 个答案:

答案 0 :(得分:1)

GET方法中的foreach循环正在遍历视图模型的SecondaryImages属性,该属性只是一个空集合。您需要遍历数据模型的Images集合,并初始化ImageVM的新实例,然后添加到视图模型SecondaryImages集合。

Furniture furniture = db.Furnitures.Find(id);
IEnumerable<FurnitureImages> images = furniture.Images; // all images
FurnitureImages mainImage = images.Where(x => x.IsMainImage).FirstOrDefault();
IEnumerable<FurnitureImages> secondaryImages = images.Where(x => !x.IsMainImage);
FurnitureVM model = new FurnitureVM()
{
    Name = furniture.Name,
    .... // set other properties
    MainImage = new ImageVM()
    {
        Id = mainImage.Id,
        DisplayName = mainImage.DisplayName,
        ....
    },
    SecondaryImages = secondaryImages.Select(x => new ImageVM()
    {
        Id = x.Id,
        Path = x.Path,
        DisplayName = x.DisplayName
    }).ToList()
};
return View(model);

请注意,除非您在视图中为其生成复选框,否则视图模型中的bool IsMainImage属性似乎是不必要的。

此外,我建议您遵循惯例并将FurnitureImages(复数)重命名为FurnitureImage,因为它描述了一个对象。