在编辑方法中上传多个图像不正确

时间:2017-02-25 21:43:30

标签: c# asp.net asp.net-mvc

我有方法Edit,将主页面的一个图像和图库的多个图像上传到数据库中的现有记录。我有一对多的关系表(FurnitureImages我存储有关图像的信息),我也使用View Model 所以我的代码

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(FurnitureVM model)
{
    if (model.MainFile != null && model.MainFile.ContentLength > 0)
    {
        string displayName = model.MainFile.FileName;
        string extension = Path.GetExtension(displayName);
        string fileName = string.Format("{0}{1}", Guid.NewGuid(), extension);
        string path = "~/Upload/" + fileName;
        model.MainFile.SaveAs(Server.MapPath( path));
        model.MainImage = new ImageVM() { Path = path, DisplayName = displayName };
    }     
    foreach (HttpPostedFileBase file in model.SecondaryFiles)
    {
        FurnitureImages images = new FurnitureImages();
        if (file != null && file.ContentLength > 0)
        {
            string displayName = file.FileName;
            string extension = Path.GetExtension(displayName);
            string fileName = string.Format("{0}{1}", Guid.NewGuid(), extension);
            var path = "~/Upload/" + fileName;
            file.SaveAs(Server.MapPath(path));
            model.SecondaryImages = new List<ImageVM> { new ImageVM { DisplayName = displayName, Path = path } };
        }
    }
    if (!ModelState.IsValid)
    {
        model.CategoryList = new SelectList(db.Categories, "CategoryId", "Name",model.CategoryId); // repopulate the SelectList
        return View(model);
    }

    Furniture furniture = db.Furnitures.Where(x => x.FurnitureId == model.ID).FirstOrDefault();
    FurnitureImages main = furniture.Images.Where(x => x.IsMainImage).FirstOrDefault();
    furniture.Name = model.Name;
    furniture.Description = model.Description;
    furniture.Manufacturer = model.Manufacturer;
    furniture.Price = model.Price;
    furniture.CategoryId = model.CategoryId;
    furniture.Size = model.Size;       
    main.DisplayName = model.MainImage.DisplayName;
    main.Path = model.MainImage.Path;
    main.IsMainImage = model.MainImage.IsMainImage;
    if (model.MainImage != null && !model.MainImage.Id.HasValue)
    {
        FurnitureImages image = new FurnitureImages
        {
            Path = model.MainImage.Path,
            DisplayName = model.MainImage.DisplayName,
            IsMainImage = true
        };
        furniture.Images.Add(image);
        db.Entry(furniture).State = EntityState.Modified;
    } 
    // Update secondary images
    IEnumerable<ImageVM> newImages = model.SecondaryImages.Where(x => x.Id == null);
    foreach (ImageVM image in newImages)
    {
        FurnitureImages images = new FurnitureImages
        {
            DisplayName = image.DisplayName,
            Path =  image.Path , 
            IsMainImage = false
        };
        furniture.Images.Add(images);
    }
    ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "Name", furniture.CategoryId);
    db.SaveChanges();
    return RedirectToAction("Index");
}

主图片上传效果不错,但是当我尝试从其他输入文件上传多张图片时

@Html.TextBoxFor(m => m.SecondaryFiles, new { type = "file", multiple = "multiple" , name = "SecondaryFiles" })
@Html.ValidationMessageFor(m => m.SecondaryFiles)
@for (int i = 0; i < Model.SecondaryImages.Count; i++)
{
    @Html.HiddenFor(m => m.SecondaryImages[i].Id)
    @Html.HiddenFor(m => m.SecondaryImages[i].Path)
    @Html.HiddenFor(m => m.SecondaryImages[i].DisplayName)
    <img src="@Url.Content(Model.SecondaryImages[i].Path)" />
}

它只上传了一张图片,而且我一直尝试上传很多图片,但它总是只上传一张,所以我的方法中的错误在哪里?

1 个答案:

答案 0 :(得分:1)

您的问题是,在第一个foreach循环内,您正确地将每个文件保存到服务器,但在每次迭代中,您创建一个新的List<ImageVM>并覆盖SecondaryImages的值所以当循环完成时,它只包含一个项目(基于最后一个图像)。

将循环更改为

foreach (HttpPostedFileBase file in model.SecondaryFiles)
{
    // FurnitureImages images = new FurnitureImages(); -- DELETE
    if (file != null && file.ContentLength > 0)
    {
        string displayName = file.FileName;
        string extension = Path.GetExtension(displayName);
        string fileName = string.Format("{0}{1}", Guid.NewGuid(), extension);
        var path = "~/Upload/" + fileName;
        file.SaveAs(Server.MapPath(path));
        // Add a new ImageVM to the collection 
        model.SecondaryImages.Add(new ImageVM { DisplayName = displayName, Path = path });
    }
}

请注意,上面假设您的视图模型具有初始化SecondaryImages的无参数构造函数。如果没有,则在循环之前添加model.SecondaryImages = new List<ImageVM>

要解决的其他一些小问题。

  1. 生成SelectList的代码应该是公正的 model.CategoryList = new SelectList(db.Categories, "CategoryId", "Name"); - SelectList构造函数的最后一个参数是 绑定到模型属性时忽略,因此它没有意义。
  2. 删除ViewBag.CategoryId = new SelectList(...)代码行。 您的模型已包含SelectList的属性(根据 注意1)但无论如何,你的重定向,所以添加任何东西 ViewBag毫无意义。
  3. 移动db.Entry(furniture).State = EntityState.Modified;行 紧接在db.SaveChanges();
  4. 之前的代码