MVC 5中的图片库

时间:2015-07-18 08:09:35

标签: asp.net-mvc-5

我目前正在处理图片库(或带有图片的产品),并且在我的ProductsController中的UploadImageMethod中出现了一个奇怪的错误。这是方法,然后我将解释错误的位置:

[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");
}
}

我在这一行收到错误:

ProductImages.Add(new ProductImage() { Path = Server.MapPath("~/Content/ProductImages/") + name, AltText = name })

它表示"无效的初始化成员声明符" ,它还说当前上下文中不存在ProductImages。如果您需要在此处查看Product类,那么它是:

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; }
}

有人能告诉我我做错了吗?

修改

当我这样做时,我没有错误

var p = new Product();

    p.ProductId = Guid.NewGuid();
    p.ProductName = name;
    p.ProductImages.Add(new ProductImage() { Path = Server.MapPath("~/Content/ProductImages/") + name, AltText = name });

任何人都有这方面的解释吗?