I have view where we can see existing image and I want to upload new images to existing , so images uploads to folders and info about image storing in database also I use view model My View Models Class
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; }
}
My Edit Method
[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);
}
So image's info writes to db good , but when I go to Edit View second time I get an exception "object reference not set to an instance of an object"
in line string displayName = file.FileName;
I understand that I must create an instance of FurnitureImages , right? Okay then how I have to write code , something like this? images.DisplayName = file.Filename
etc?? And Is my foreach loop right where i update? Thank you