在Edit POST方法中上传新图像

时间:2017-02-18 00:31:06

标签: asp.net asp.net-mvc

我查看了我们可以看到现有图像的位置,并且我想将新图像上传到现有图像,因此图像上传到文件夹以及有关图像存储在数据库中的信息我也使用视图模型 我的视图模型类

public class FurnitureVM
{
    ...
    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; }
}

我的编辑方法

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(FurnitureVM model)
{
    // Save the files
    foreach (HttpPostedFileBase file in model.SecondaryFiles)
    {
        FurnitureImages images = new FurnitureImages();
        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 } };
    }
    // 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);
}

所以image的信息写入db good,但是当我第二次进入Edit View时,我在行"object reference not set to an instance of an object"中得到异常string displayName = file.FileName;我明白我必须创建一个FurnitureImages实例,对吗?那么我必须编写代码,这样的事情呢? images.DisplayName = file.Filename等?我的foreach循环在我更新的地方吗?谢谢

0 个答案:

没有答案