public async Task <IActionResult> Create(ProductsCreateVm createVm) { if (ModelState.IsValid) { Category category = await _cRepository.GetByIdAsync(createVm.CategoryId.Value); if (category != null) { Product createdProduct = new Product { Name = createVm.Name, Description = createVm.Description, Price = createVm.Price, PhotoUrl = createVm.PhotoUrl, SortNumber = createVm.SortNumber, Category = category }; createdProduct.PhotoUrl = await SaveProductImage(createVm.UploadedImage); await _pRepository.AddAsync(createdProduct); TempData[Constants.SuccessMessage] = $"Product \"{createdProduct.Name}\" has been created"; return(RedirectToAction(nameof(Index))); } else { ModelState.AddModelError(nameof(createVm.CategoryId), "This category doesn't exist"); } } createVm.AvailableCategories = _cRepository.GetAll().OrderBy(e => e.Name); return(View(createVm)); }
// GET: Admin/Products/Create public IActionResult Create() { var viewModel = new ProductsCreateVm { Price = 0 }; viewModel.AvailableCategories = _cRepository.GetAll().OrderBy(e => e.Name); return(View(viewModel)); }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { ProductsCreateVm vm = validationContext.ObjectInstance as ProductsCreateVm; if (vm?.UploadedImage != null) { if (vm.UploadedImage.Length > _maxLength * 1024) { return(new ValidationResult($"The file cannot exceed {_maxLength} kB")); } else if (!_allowedExtensions .Any(ext => ext == Path.GetExtension(vm.UploadedImage.FileName).ToLower())) { string allowedExt = _allowedExtensions.Aggregate((cur, next) => cur + ", " + next); return(new ValidationResult( $"The file must be one of {allowedExt}")); } } return(ValidationResult.Success); }