Uploading images in MVC 5

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • PsychoCoder
    Recognized Expert Contributor
    • Jul 2010
    • 465

    Uploading images in MVC 5

    I'm currently working on an image gallery (or products with their images) and am getting a weird error in the UploadImageMeth od in my ProductsControl ler. Here's the method, then I'll explain where the error is:

    Code:
     [HttpPost]
        public ActionResult UploadImageMethod()
        {
            //make sure we have files to upload
            if (Request.Files.Count != 0)
            {
                //Parallel.For loop to loop through each image being uploaded
                Parallel.For(0, Request.Files.Count, index =>
                    {
                        //new HttpPostedFileBase to hold each image with
                        HttpPostedFileBase file = Request.Files[index];
        
                        //get the file size
                        int size = file.ContentLength;
        
                        //get the file name
                        string name = file.FileName;
        
                        //save the image to our desired directory
                        file.SaveAs(Server.MapPath("~/Content/ProductImages/") + name);
        
                        //now create a new Product and set it's properties
                        Product p = new Product()
                        {
                            ProductId = Guid.NewGuid(),
                            ProductName = name,
                            ProductImages.Add(new ProductImage() { Path = Server.MapPath("~/Content/ProductImages/") + name, AltText = name })
                        };
        
                        //add it to the database
                        db.Products.Add(p);
        
                        //save the changes
                        db.SaveChanges();
                    });
                return Content("Success");
            }
            return Content("failed");
        }
        }
    I'm getting the error on this line:

    Code:
     ProductImages.Add(new ProductImage() { Path = Server.MapPath("~/Content/ProductImages/") + name, AltText = name })
    It says "invalid initializer member declarator" , it also says ProductImages does not exist in the current context. If you need to see the Product class here it is:

    Code:
    public class Product
        {
            public Product()
            {
                ProductImages = new List<ProductImage>();
            }
        
            public int ProductId { get; set; }
        
            public string ProductName { get; set; }
            public double ProductPrice { get; set; }
            public int ProductQuantity { get; set; }
        
            public virtual List<ProductImage> ProductImages { get; set; }
        }
    Can someone tell me what I'm doing wrong?
Working...