public async Task <IActionResult> Create(ProductViewModel viewModel)
        {
            Product product = new Product();

            product.Name                 = viewModel.Name;
            product.Description          = viewModel.Description;
            product.Price                = viewModel.Price;
            product.CategoryID           = viewModel.CategoryID;
            product.ProductImageMappings = new List <ProductImageMapping>();
            //get a list of selected images without any blanks
            string[] productImages = viewModel.ProductImages.Where(pi => !string.IsNullOrEmpty(pi)).ToArray();
            for (int i = 0; i < productImages.Length; i++)
            {
                product.ProductImageMappings.Add(new ProductImageMapping
                {
                    ProductImage = _context.ProductImage.Find(int.Parse(productImages[i])),
                    ImageNumber  = i
                });
            }
            if (ModelState.IsValid)
            {
                _context.Add(product);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            viewModel.CategoryList = new SelectList(_context.Set <Category>(), "ID", "Name", product.CategoryID);
            viewModel.ImageLists   = new List <SelectList>();
            for (int i = 0; i < Constants.NumberOfProductImages; i++)
            {
                viewModel.ImageLists.Add(new SelectList(_context.Set <ProductImage>(), "ID", "FileName", viewModel.ProductImages[i]));
            }
            return(View(viewModel));
        }
        public async Task <IActionResult> Create([Bind("ID,Name")] Category category)
        {
            if (ModelState.IsValid)
            {
                _context.Add(category);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(category));
        }
Beispiel #3
0
        public async Task <IActionResult> Upload(IFormFile[] files)
        {
            bool   allValid     = true;
            string inValidFiles = "";

            //check the user has entered a file
            if (files.Length != 0)
            {
                //if the user has entered less than 10 files
                if (files.Length <= 10)
                {
                    foreach (var file in files)
                    {
                        if (!ValidateFile(file))
                        {
                            allValid      = false;
                            inValidFiles += ", " + Path.GetFileName(file.FileName);
                        }
                    }
                    //if they are valid then try to save them to disk
                    if (allValid)
                    {
                        foreach (var file in files)
                        {
                            try
                            {
                                SaveFileToDiskAsync(file);
                            }
                            catch (Exception)
                            {
                                ModelState.AddModelError("FileName", "Sorry an error occurred saving the file to disk, please try again");
                            }
                        }
                    }
                    //else add an error listing out the invalid files
                    else
                    {
                        ModelState.AddModelError("FileName", "All files must be gif, png, jpeg or jpg and less than 2MB in size.The following files" + inValidFiles + " are not valid");
                    }
                }
                //the user has entered more than 10 files
                else
                {
                    ModelState.AddModelError("FileName", "Please only upload up to ten files at a time");
                }
            }
            else
            {
                //if the user has not entered a file return an error message
                ModelState.AddModelError("FileName", "Please choose a file");
            }

            if (ModelState.IsValid)
            {
                bool   duplicates     = false;
                bool   otherDbError   = false;
                string duplicateFiles = "";

                foreach (var file in files)
                {
                    //try and save each file
                    var productToAdd = new ProductImage {
                        FileName = Path.GetFileName(file.FileName)
                    };
                    try
                    {
                        _context.Add(productToAdd);
                        await _context.SaveChangesAsync();
                    }
                    //if there is an exception check if it is caused by duplicate file
                    catch (DbUpdateException ex)
                    {
                        SqlException innerException = ex.InnerException as SqlException;
                        if (innerException != null && innerException.Number == 2601)
                        {
                            duplicateFiles += "," + Path.GetFileName(file.FileName);
                            duplicates      = true;
                            _context.Entry(productToAdd).State = EntityState.Detached;
                        }
                        else
                        {
                            otherDbError = true;
                        }
                    }
                }

                //add a list of duplicate files to the error message
                if (duplicates)
                {
                    ModelState.AddModelError("FileName", "All files uploaded except the files" + duplicateFiles
                                             + ", which already exist in the system ." + " Please delete them and try again if you wish to re-add them");
                    return(View());
                }
                else if (otherDbError)
                {
                    ModelState.AddModelError("FileName", "Sorry an error has occurred saving to the database, please try again");
                    return(View());
                }

                return(RedirectToAction(nameof(Index)));
            }
            return(View());
        }