コード例 #1
0
        public IActionResult Edit(ProductModel model, List <IFormFile> files)
        {
            if (ModelState.IsValid)
            {
                var updatedResult = _productService.Update(model);

                if (updatedResult.Success)
                {
                    if (files != null && files.Any())
                    {
                        List <ProductImage> images = new List <ProductImage>();
                        for (int i = 0; i < files.Count; i++)
                        {
                            var extention = Path.GetExtension(files[i].FileName);
                            var name      = string.Format($"{model.Name}_{i}{extention}");
                            images.Add(new ProductImage
                            {
                                ProductId = model.Id,
                                Url       = $"~/images/{name}"
                            });
                            var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images", name);

                            using var stream = new FileStream(path, FileMode.Create);
                            files[i].CopyTo(stream);
                        }

                        var existImages = _productImageService.GetImagesByProductId(model.Id);
                        if (existImages.Any())
                        {
                            _productImageService.DeleteImages(existImages);
                            _productImageService.InsertImages(images);
                        }
                    }

                    TempData["Message"] = updatedResult.Message;
                    return(RedirectToAction("Index", "ProductAdmin"));
                }
                else
                {
                    TempData["Message"] = updatedResult.Message;
                    return(View(model));
                }
            }

            return(View(model));
        }