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