1

I am trying to create a product with multiple images in 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.

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

1 Answer 1

2

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.

[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));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.