简体   繁体   English

如何在 ASP.NET Core MVC 中创建具有多个图像的产品

[英]How to create product with multiple images in ASP.NET Core MVC

I am trying to create a product with multiple images in ASP.NET Core MVC.我正在尝试在 ASP.NET Core MVC 中创建具有多个图像的产品。 In controller we can upload the product information and images, but don't know how to update the relevant images information in database.在controller我们可以上传产品信息和图片,但是不知道如何更新数据库中的相关图片信息。

Can you please show me the code to insert the images name in images table?你能告诉我在图像表中插入图像名称的代码吗?

public class Product
{
        public int Id { get; set; }
        public string Name { get; set; }
        public String Description { get; set; }
        public ICollection<Product_Images> product_Images { get; set; }
}

public class Product_Images
{
        public int ID { get; set; }
        public string ImageName { get; set; }

        public int ProductId { get; set; }

        [ForeignKey("ProductId")]
        public Product product { get; set; }
}
 
public class ProductViewModel
{
    public Product Product { get; set; }
    public IEnumerable<SubCategory> SubCategory { get; set; }
    public List<Product_Images> product_Images { get; set; }
}

public class ProductsController : Controller
{
        private readonly ApplicationDbContext _db;
        private readonly IWebHostEnvironment _hostingEnvironment;

        [BindProperty]
        public ProductViewModel ProductVM { get; set; }

        public ProductsController(ApplicationDbContext db, IWebHostEnvironment hostingEnvironment)
        {
            _db = db;
            _hostingEnvironment = hostingEnvironment;

            ProductVM = new ProductViewModel()
            {
                Category = _db.Category,
                Product = new Models.Product()
            };
        }

        [HttpPost, ActionName("Create")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> CreatePost()
        {
            ProductVM.Product.SubCategoryId = Convert.ToInt32(Request.Form["SubCategoryId"].ToString());

            if (!ModelState.IsValid)
            {
                return View(ProductVM);
            }

            _db.Product.Add(ProductVM.Product);
            await _db.SaveChangesAsync();

            var ProductFromDb = await _db.Product.FindAsync(ProductVM.Product.Id);

            string webRootPath = _hostingEnvironment.WebRootPath;
            var files = HttpContext.Request.Form.Files;

            if (files.Count > 0)
            {
                foreach (var item in files)
                {
                    var uploads = Path.Combine(webRootPath, "images");
                    var extension = Path.GetExtension(item.FileName);
                    var dynamicFileName = Guid.NewGuid().ToString() + "_" + ProductVM.Product.Id + extension;

                    using (var filesStream = new FileStream(Path.Combine(uploads, dynamicFileName), FileMode.Create))
                    {
                        item.CopyTo(filesStream);
                    }
                }
            }

            await _db.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
    }
}

I am trying to create a product with multiple images.我正在尝试创建具有多个图像的产品。 We can upload the product information and images, but don't know how to update the relevant images information in database.我们可以上传产品信息和图片,但不知道如何更新数据库中的相关图片信息。

To add new product with multiple Product_Images to your database, you can try following code snippet.要将具有多个 Product_Image 的新产品添加到您的数据库中,您可以尝试以下代码片段。

[HttpPost, ActionName("Create")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreatePost()
{
    //your code logic here
    //...

    if (!ModelState.IsValid)
    {
        return View(ProductVM);
    }

    //...

    //create new product

    var newproduct = new Product
    {
        Name = ProductVM.Product.Name,
        Description = ProductVM.Product.Description,
        product_Images = new List<Product_Images> { }
    };

    //...

    string webRootPath = _hostingEnvironment.WebRootPath;
    var files = HttpContext.Request.Form.Files;

    if (files.Count > 0)
    {
        foreach (var item in files)
        {
            var uploads = Path.Combine(webRootPath, "images");
            var extension = Path.GetExtension(item.FileName);
            var dynamicFileName = Guid.NewGuid().ToString() + "_" + ProductVM.Product.Id + extension;

            using (var filesStream = new FileStream(Path.Combine(uploads, dynamicFileName), FileMode.Create))
            {
                item.CopyTo(filesStream);
            }

            //add product Image for new product
            newproduct.product_Images.Add(new Product_Images { ImageName = dynamicFileName });
        }
    }


    await _db.Product.AddAsync(newproduct);
    await _db.SaveChangesAsync();

    return RedirectToAction(nameof(Index));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM