0

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

Muhammed Shevil KP
  • 1,404
  • 1
  • 16
  • 21
M-Misha-M
  • 33
  • 9
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Roman Marusyk Feb 18 '17 at 00:35
  • Add a check in the `foreach` loop - `foreach (HttpPostedFileBase file in model.SecondaryFiles) { if (file != null && file.ContentLength > 0) { ... ` –  Feb 18 '17 at 00:59
  • @StephenMuecke hmmm good , now it works....i think :) – M-Misha-M Feb 18 '17 at 01:13

0 Answers0