public async Task <IActionResult> Edit(EditProductInputModel inputModel) { if (!ModelState.IsValid) { var allCategories = this.categoryService.GetAllCategories <ProductCategoryViewModel>().ToList(); var categories = allCategories.Select(x => new SelectListItem() { Text = x.Name }).ToList(); inputModel.Categories = categories; return(this.View(inputModel)); } var product = this.mapper.Map <Product>(inputModel); var user = await this.userManager.GetUserAsync(HttpContext.User); product.MarketplaceUserId = user.Id; var category = await this.categoryService.GetCategoryByName(inputModel.CategoryName); product.CategoryId = category.Id; var editedProduct = await this.productService.EditProduct(product); var picturePath = await this.pictureService .SavePicture(editedProduct.Id, inputModel.Picture, GlobalConstants.DefaultPicturesPath); await this.productService.EditPicturePath(editedProduct.Id, picturePath); return(this.RedirectToAction(nameof(My))); }
public async Task UpdateAsync(string id, EditProductInputModel input) { var products = this.productsRepository.All().FirstOrDefault(x => x.Id == id); products.Name = input.Name; products.Description = input.Description; products.Price = input.Price; products.Availability = input.Availability; products.CategoryId = input.CategoryId; await this.productsRepository.SaveChangesAsync(); }
public async Task <IActionResult> EditProduct(EditProductInputModel input, int id) { if (!this.ModelState.IsValid) { return(this.View()); } await this.productsService.EditProductAsync(input, id); return(this.RedirectToAction(nameof(this.Success))); }
public async Task <IActionResult> Edit(EditProductInputModel input) { if (!ModelState.IsValid) { return(this.View()); } await this.productsService.UpdateAsync(input); return(this.RedirectToAction("Index")); }
public async Task <IActionResult> Edit(EditProductInputModel input) { if (!this.ModelState.IsValid) { return(this.View(input)); } await this.productService.UpdateAsync(input.Id, input.Name, input.Price, input.Quantity, input.BarCode, input.CategoryId); return(this.RedirectToAction(RedirectIndex, RedirectWareHouse)); }
public async Task <IActionResult> Edit(string id, EditProductInputModel input) { if (!this.ModelState.IsValid) { input.CategoriesItems = this.categoriesService.GetAllAsKeyValuePairs(); return(this.View(input)); } await this.productsService.UpdateAsync(id, input); return(this.RedirectToAction(nameof(this.ById), new { id })); }
public async Task EditProductAsync(string id, EditProductInputModel input) { var product = await this.productsRepository.AllWithDeleted().FirstOrDefaultAsync(x => x.Id == id); product.Price = input.Price; product.Title = input.Title; product.Category = input.Category; product.SubCategory = input.SubCategory; product.Description = input.Description; this.productsRepository.Update(product); await this.productsRepository.SaveChangesAsync(); }
public async Task <IActionResult> Edit(EditProductInputModel model, List <IFormFile> files) { if (!this.ModelState.IsValid) { return(this.View(model)); } var id = await this.productsService.Edit(model.Id, model.CategoryId, model.Name, model.Description, model.Price); this.imagesService.UploadImagesToProduct(model.Id, files); return(this.RedirectToAction("Details", new { id = model.Id })); }
public async Task EditProductAsync(EditProductInputModel input, int id) { var product = this.productsRepository .All() .FirstOrDefault(x => x.Id == id); product.Name = input.Name; product.Details = input.Details; product.Price = input.Price; product.UnitsPerCase = input.UnitsPerCase; product.AvailableUnits = input.AvailableUnits; await this.productsRepository.SaveChangesAsync(); }
public async Task <IActionResult> Edit(int productId, EditProductInputModel input) { if (!this.ModelState.IsValid) { return(this.Ok(input)); } var result = await this.productService.EditProductAsync(productId, input); if (result) { return(this.Ok()); } return(this.BadRequest()); }
public async Task UpdateAsync(int id, EditProductInputModel inputModel) { var products = this.productsRepository .AllAsNoTrackingWithDeleted() .FirstOrDefault(x => x.Id == id); if (products != null) { products.Name = inputModel.Name; products.Brand = inputModel.Brand; products.ProductCode = inputModel.ProductCode; products.Stock = inputModel.Stock; products.Price = inputModel.Price; products.Description = inputModel.Description; products.CategoryId = inputModel.CategoryId; } await this.productsRepository.SaveChangesAsync(); }
public async Task <int> UpdateAsync(EditProductInputModel input) { var product = await this.productsRepository.GetByIdWithDeletedAsync(input.Id); product.Name = input.Name; product.Description = input.Description; product.Price = input.Price; product.Quantity = input.Quantity; if (input.ProductPicture != null) { var productPictureUrl = await this.cloudinaryService.UploadAsync(input.ProductPicture); product.ProductPictureUrl = productPictureUrl; } this.productsRepository.Update(product); return(await this.productsRepository.SaveChangesAsync()); }
public async Task <bool> EditProductAsync(int id, EditProductInputModel input) { var currentProduct = this.GetProductById(id); if (currentProduct != null) { currentProduct.Name = input.Name; currentProduct.CategoryName = input.CategoryName; currentProduct.CategoryType = input.CategoryType; currentProduct.Sizes = input.Sizes; currentProduct.Colors = input.Colors; currentProduct.Price = input.Price; currentProduct.Description = input.Description; currentProduct.Pictures = (ICollection <Picture>)input.Pictures; this.productRepository.Update(currentProduct); await this.productRepository.SaveChangesAsync(); return(true); } throw new InvalidOperationException(GlobalConstants.ProductEditError); }
public async Task <IActionResult> Put([FromBody] EditProductInputModel input) { if (!ModelState.IsValid) { return(BadRequest(GetErrorListFromModelState.GetErrorList(ModelState))); } if (!TypesManager.checkStatus(input.Type)) { return(BadRequest(new { errors = new { Type = ErrorConst.InvalidType } })); } var product = _context.Products.Where(i => i.Id == input.Id).FirstOrDefault(); if (product != null) { try { product.Name = input.Name; product.Description = input.Description; product.Type = input.Type; product.OwnerId = input.OwnerId; _context.Products.Update(product); await _context.SaveChangesAsync(); return(Ok()); } catch (Exception ex) { return(GetCatchExceptionErrors.getErrors(this, ex)); } } else { return(BadRequest(new { errors = new { Id = ErrorConst.NO_ITEM } })); } }
public async Task <Tuple <string, string> > EditProduct(EditProductInputModel inputModel) { var product = await this.db.Products.FirstOrDefaultAsync(x => x.Id == inputModel.Id); if (product != null) { var category = await this.db.ProductCategories .FirstOrDefaultAsync(x => x.Title.ToLower() == inputModel.ProductCategory.ToLower()); if (category != null) { product.ProductCategoryId = category.Id; product.Name = inputModel.Name; product.Description = inputModel.SanitaizedDescription; product.AvailableQuantity = inputModel.AvailableQuantity; product.SpecificationsDescription = inputModel.SanitaizedSpecifications; product.Price = inputModel.Price; product.UpdatedOn = DateTime.UtcNow; if (inputModel.ProductImages.Count != 0) { var images = this.db.ProductImages.Where(x => x.ProductId == inputModel.Id).ToList(); foreach (var image in images) { ApplicationCloudinary.DeleteImage(this.cloudinary, image.Name); } this.db.ProductImages.RemoveRange(images); await this.db.SaveChangesAsync(); for (int i = 0; i < inputModel.ProductImages.Count(); i++) { var imageName = string.Format(GlobalConstants.ProductImageName, product.Id, i); var imageUrl = await ApplicationCloudinary.UploadImage( this.cloudinary, inputModel.ProductImages.ElementAt(i), imageName); if (imageUrl != null) { var image = new ProductImage { ImageUrl = imageUrl, Name = imageName, ProductId = product.Id, }; product.ProductImages.Add(image); } } } this.db.Products.Update(product); await this.db.SaveChangesAsync(); return(Tuple.Create("Success", SuccessMessages.SuccessfullyEditedProduct)); } return(Tuple.Create("Error", ErrorMessages.InvalidInputModel)); } return(Tuple.Create("Error", ErrorMessages.InvalidInputModel)); }
public async Task <IActionResult> Edit(EditProductInputModel inputModel) { //Set input model short description inputModel.ShortDescription = this.productService.GetShordDescription(inputModel.Description, 40); //Store input model for passing in get action TempData[GlobalConstants.InputModelFromPOSTRequest] = JsonSerializer.Serialize(inputModel); TempData[GlobalConstants.InputModelFromPOSTRequestType] = nameof(EditProductInputModel); //Check without looking into the database if (this.ModelState.IsValid == false) { //Store needed info for get request in TempData only if the model state is invalid after doing the complex checks TempData[GlobalConstants.ErrorsFromPOSTRequest] = ModelStateHelper.SerialiseModelState(this.ModelState); return(this.RedirectToAction(nameof(Edit), "Products", new { productId = inputModel.Id })); } //Check if product with this id exists if (this.productService.ProductExistsById(inputModel.Id) == false) { this.ModelState.AddModelError("", "The product that you are trying to edit doesn't exist."); } var productId = inputModel.Id; //Check if product with this model or name exist and it is not the product that is currently being edited if (this.productService.ProductExistsByModel(inputModel.Model, productId) == true) { this.ModelState.AddModelError("Model", "Product with this model already exists."); } if (this.productService.ProductExistsByName(inputModel.Name, productId)) { this.ModelState.AddModelError("Name", "Product with this name already exists."); } //Check if there is a main image, regardless of the imageMode if ((inputModel.MainImage == null && inputModel.ImagesAsFileUploads == false) || (inputModel.MainImageUploadInfo.ImageUpload == null && inputModel.MainImageUploadInfo.IsBeingModified && inputModel.ImagesAsFileUploads == true)) { this.ModelState.AddModelError("", "Main image is required"); //Store needed info for get request in TempData only if the model state is invalid after doing the complex checks TempData[GlobalConstants.ErrorsFromPOSTRequest] = ModelStateHelper.SerialiseModelState(this.ModelState); return(this.RedirectToAction(nameof(Edit), "Products", new { productId = productId })); } //CHECK THE IMAGES LINKS if (inputModel.ImagesAsFileUploads == false) { //Check if all of these images are unique if (this.productImageService.ImagesAreRepeated(inputModel.MainImage, inputModel.AdditionalImages)) { this.ModelState.AddModelError("", "There are 2 or more non-unique images"); } //Check if main image is already used by OTHER products if (this.productImageService.ProductImageExists(inputModel.MainImage, productId) == true) { this.ModelState.AddModelError("MainImage", "This image is already used."); } if (inputModel.AdditionalImages == null) { inputModel.AdditionalImages = new List <string>(); } //Check if any of the additional images are used by OTHER products for (int i = 0; i < inputModel.AdditionalImages.Count; i++) { var additionalImage = inputModel.AdditionalImages[i]; if (this.productImageService.ProductImageExists(additionalImage, productId) == true) { this.ModelState.AddModelError($"AdditionalImages[{i}]", "This image is already used."); } } } //CHECK IMAGES UPLOADS else { var mainImageUpload = inputModel.MainImageUploadInfo.ImageUpload; //Check main image upload extension is valid, but only if the user has actually selected a file themselves if (inputModel.MainImageUploadInfo.IsBeingModified && this.productImageService.ValidImageExtension(mainImageUpload) == false) { this.ModelState.AddModelError("MainImageUploadInfo.ImageUpload", "The uploaded image is invalid"); } if (inputModel.AdditionalImagesUploadsInfo == null) { inputModel.AdditionalImagesUploadsInfo = new List <EditProductImageUploadInputModel>(); } var additionalImagesUploads = inputModel.AdditionalImagesUploadsInfo .Select(x => x.ImageUpload) .Where(imageUpload => imageUpload != null) .ToList(); //Check additional images uploads for (int i = 0; i < additionalImagesUploads.Count; i++) { var imageUpload = additionalImagesUploads[i]; if (imageUpload != null && this.productImageService.ValidImageExtension(imageUpload) == false) { this.ModelState.AddModelError($"AdditionalImagesUploadsInfo[{i}].ImageUpload.", "The uploaded image is invalid"); } } } //Check if categories exist in the database or if there are even any categories for this product for (int i = 0; i < inputModel.CategoriesIds.Count; i++) { var categoryId = inputModel.CategoriesIds[i]; if (this.categoryService.CategoryExists(categoryId) == false) { this.ModelState.AddModelError($"CategoriesIds{i}", "This category doesn't exist"); } } if (inputModel.CategoriesIds.Count == 0) { this.ModelState.AddModelError("", "You need to add at least one category for this product"); } //Check if categories exist in the database for (int i = 0; i < inputModel.CategoriesIds.Count; i++) { var categoryId = inputModel.CategoriesIds[i]; if (this.categoryService.CategoryExists(categoryId) == false) { this.ModelState.AddModelError($"CategoriesIds{i}", "This category doesn't exist"); } } //Check if categories are unique if (inputModel.CategoriesIds.Where(x => string.IsNullOrWhiteSpace(x) == false).Distinct().Count() != inputModel.CategoriesIds.Where(x => string.IsNullOrWhiteSpace(x) == false).Count()) { this.ModelState.AddModelError($"", "One category cannot be used multiple times."); } if (this.ModelState.IsValid == false) { //Store needed info for get request in TempData only if the model state is invalid after doing the complex checks TempData[GlobalConstants.ErrorsFromPOSTRequest] = ModelStateHelper.SerialiseModelState(this.ModelState); return(this.RedirectToAction(nameof(Edit), "Products", new { productId = inputModel.Id })); } await this.productService.EditAsync(inputModel); var product = this.productService.GetProductById(inputModel.Id, false); await this.categoryService.EditCategoriesToProductAsync(product, inputModel.CategoriesIds); //Set notification NotificationHelper.SetNotification(this.TempData, NotificationType.Success, "Product was successfully edited"); return(this.RedirectToAction("ProductPage", "Products", new { area = "", productId = inputModel.Id })); }
public async Task EditAsync(EditProductInputModel inputModel) { var productToEdit = this.context.Products .Include(x => x.Images) .First(x => x.Id == inputModel.Id); //Edit images as links if (inputModel.ImagesAsFileUploads == false) { //Remove all of the images for the product productToEdit.Images.Clear(); this.context.RemoveRange(this.context.ProductsImages .Where(x => x.ProductId == productToEdit.Id)); //Edit main image link for product var mainImage = new ProductImage { Image = inputModel.MainImage, ProductId = productToEdit.Id, IsMain = true }; productToEdit.Images.Add(mainImage); var newAdditionalImages = inputModel.AdditionalImages.Where(x => x != null).ToList(); //Edit additional images links for product for (int i = 0; i < newAdditionalImages.Count; i++) { var newImagePath = newAdditionalImages[i]; var newImage = new ProductImage { Image = newImagePath, ProductId = productToEdit.Id, Product = productToEdit }; productToEdit.Images.Add(newImage); } } //Edit images as uploads else if (inputModel.ImagesAsFileUploads == true) { //Change main image if set to be modified if (inputModel.MainImageUploadInfo.IsBeingModified == true) { var mainImageInfo = inputModel.MainImageUploadInfo; await this.productImageService.EditImageAsync(mainImageInfo, productToEdit); } //Change all additional images if set to be modified var additionalImagesInfo = inputModel.AdditionalImagesUploadsInfo; foreach (var additionalImageInfo in additionalImagesInfo) { if (additionalImageInfo.IsBeingModified == true) { await this.productImageService.EditImageAsync(additionalImageInfo, productToEdit); ////Get the main image from the database //var image = this.productImageService.GetImageById(additionalImageInfo.ModifiedImage.Id); ////Upload main image to azure blob storage //var imageUri = await this.productImageService.UploadImageAsync(additionalImageInfo.ImageUpload, productToEdit); ////Set the main image uri in the database //image.Image = imageUri; } } } //Edit all of the simple properties productToEdit.Description = inputModel.Description; productToEdit.Warranty = inputModel.Warranty; productToEdit.Model = inputModel.Model; productToEdit.Name = inputModel.Name; productToEdit.Price = inputModel.Price; productToEdit.QuantityInStock = inputModel.QuantityInStock; await context.SaveChangesAsync(); }
public IActionResult Edit(string productId) { if (this.productService.ProductExistsById(productId) == false) { NotificationHelper.SetNotification(this.TempData, NotificationType.Error, "The product doesn't exist"); return(this.RedirectToAction("ProductPage", "Products", new { area = "", productId = productId })); } EditProductInputModel inputModel = null; //Add each model state error from the last action to this one. Fill the input model with he values from the last post action if (TempData[GlobalConstants.ErrorsFromPOSTRequest] != null && TempData[GlobalConstants.InputModelFromPOSTRequestType]?.ToString() == nameof(EditProductInputModel)) { ModelStateHelper.MergeModelStates(TempData, this.ModelState); var inputModelJSON = TempData[GlobalConstants.InputModelFromPOSTRequest]?.ToString(); inputModel = JsonSerializer.Deserialize <EditProductInputModel>(inputModelJSON); var product = this.productService.GetProductById(productId, true); //Add categories names inputModel.CategoriesNames = new List <string>(); var categoriesNames = this.categoryService.GetCategoryNamesFromIds(inputModel.CategoriesIds); inputModel.CategoriesNames.AddRange(categoriesNames); //Set the image path for all of the modifiedImages if (inputModel.MainImageUploadInfo.ModifiedImage.Id != null) { inputModel.MainImageUploadInfo.ModifiedImage.Path = this.productImageService.GetImageById(inputModel.MainImageUploadInfo.ModifiedImage.Id).Image; } //Set isBeingModified param for mainImageUpload to false inputModel.MainImageUploadInfo.IsBeingModified = false; foreach (var additionalImageUploadInfo in inputModel.AdditionalImagesUploadsInfo) { var modifiedImage = additionalImageUploadInfo.ModifiedImage; if (modifiedImage.Id != null) { modifiedImage.Path = this.productImageService.GetImageById(modifiedImage.Id).Image; } //Set isBeingModified param for additionalImageUpload to false additionalImageUploadInfo.IsBeingModified = false; } } //If there wasn't an error with the edit form prior to this, just fill the inputModel like normal else { var product = this.productService.GetProductById(productId, true); inputModel = this.mapper.Map <EditProductInputModel>(product); //Get the categories for the product var productCategories = this.categoryService.GetCategoriesForProduct(product.Id).ToList(); inputModel.CategoriesIds = productCategories.Select(x => x.Id).ToList(); inputModel.CategoriesNames = productCategories.Select(x => x.Name).ToList(); //Set image mode inputModel.ImagesAsFileUploads = false; //Get the main image var mainImage = this.productImageService.GetMainImage(productId); //Set main image path inputModel.MainImage = mainImage.Image; //Set main image upload info inputModel.MainImageUploadInfo = new EditProductImageUploadInputModel { ImageUpload = null, ModifiedImage = new ImageIdAndPathInputModel { Id = mainImage.Id, Path = mainImage.Image } }; //Get additional images var additionalImages = this.productImageService.GetAdditionalImages(productId); inputModel.AdditionalImages = new List <string>(); inputModel.AdditionalImagesUploadsInfo = new List <EditProductImageUploadInputModel>(); //Sed additional images uploads and paths for (int i = 0; i < additionalImages.Count; i++) { var image = additionalImages[i]; inputModel.AdditionalImages.Add(image.Image); inputModel.AdditionalImagesUploadsInfo.Add(new EditProductImageUploadInputModel { ImageUpload = null, ModifiedImage = new ImageIdAndPathInputModel { Id = image.Id, Path = image.Image } }); } } //Set input model short description inputModel.ShortDescription = this.productService.GetShordDescription(inputModel.Description, 40); return(this.View(inputModel)); }