public void UpdateProduct(ProductEditModel productEditModel) { using (UnitOfWork unitOfWork = _unitOfWorkFactory.Create()) { unitOfWork.Products.Update(Mapper.Map <Product>(productEditModel)); } }
public IActionResult Update([FromRoute] int id, [FromBody] ProductEditModel productModel) { //TODO: Se a propriedade ImagePath foi alterado será necessário excluir a imagem antiga da estrutura de arquivos var product = _service.Update(id, productModel); return(NoContent()); }
public async Task <ActionResult <ProductViewModel> > PutProduct(string id, ProductEditModel productModel) { Product product = await _productsRepository.FindByIdAsync(id); if (product is null) { return(BadRequest($"El producto identificado con el código {id} no está registrado.")); } _mapper.Map(productModel, product); _productsRepository.Update(product); try { await _unitWork.SaveAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductExists(id)) { return(NotFound($"Error de actualización. El producto identificado con el código {id} no está registrado.")); } throw; } return(_mapper.Map <ProductViewModel>(product)); }
public IActionResult Edit(ProductEditModel model) { if (ModelState.IsValid) { var product = new Product() { ProductId = model.ProductId, CategoryId = model.CategoryId, Discontinued = model.Discontinued, ProductName = model.ProductName, QuantityPerUnit = model.QuantityPerUnit, ReorderLevel = model.ReorderLevel, SupplierId = model.SupplierId, UnitPrice = model.UnitPrice, UnitsInStock = model.UnitsInStock, UnitsOnOrder = model.UnitsOnOrder }; dbContext.Products.Update(product); dbContext.SaveChanges(); return(RedirectToAction(nameof(Index))); } else { return(View()); } }
// GET: Product/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Product product = bll.Products.GetSingle((int)id); if (product == null) { return(HttpNotFound()); } //ViewBag.SupplierID = new SelectList(db.Suppliers, "SupplierID", "Name", product.SupplierID); ProductEditModel model = new ProductEditModel(); model.Product = product; model.AllOrderItems = bll.Orders.GetAll().Select(p => new SelectListItem { Text = p.Details, Value = p.OrderID.ToString() }).ToList(); model.SelectedOrders = product.Orders.Select(p => p.OrderID).ToList(); model.SupplierItems = bll.Suppliers.GetAll().Select(c => new SelectListItem() { Text = c.Name, Value = c.SupplierID.ToString() }).ToList(); model.SupplierItems.First(c => c.Value == product.SupplierID.ToString()).Selected = true; return(View(model)); }
public ActionResult Edit(ProductEditModel model) { var product = db.Products.Find(model.ProductId); if (product != null) { product.Name = model.ProductName; product.BrandId = model.BrandId; product.CategoryId = model.CategoryId; product.Description = model.Description; product.IsVisible = model.IsVisible; product.OnSale = model.OnSale; product.SupplierId = model.SupplierId; product.Unit = model.Unit; product.UpdateDate = DateTime.Today; product.UpdateUser = User.Identity.GetUserId(); db.SaveChanges(); return(RedirectToAction("Index")); } else { ViewBag.SupplierId = new SelectList(db.Suppliers.OrderBy(x => x.Name), "SupplierId", "Name", model.SupplierId); ViewBag.BrandId = new SelectList(db.Brands.OrderBy(x => x.Name), "BrandId", "Name", model.BrandId); ViewBag.CategoryId = new SelectList(db.Categories.OrderBy(x => x.Name), "CategoryId", "Name", model.CategoryId); return(View(model)); } }
private async Task SaveProductDocument(Product product, ProductEditModel model) { var fileClient = HttpContext.RequestServices.GetRequiredService <IFileClient>(); var imageProcessor = HttpContext.RequestServices.GetRequiredService <IImageProcessor>(); await _appService.PrepareMediaAsync(new[] { product.Document }, new[] { model.Document }, createMedia : async(document) => { document.DirectoryName = product.SellerId.ToString(); var source = await fileClient.GetAsync(document.DirectoryName, document.FileName); if (source != null) { document.FileSize = source.Length; await _mediaService.CreateAsync(document); product.DocumentId = document.Id; await _productService.UpdateAsync(product); } }, updateMedia : async(document) => { await _mediaService.UpdateAsync(document); }, deleteMedia : async(document) => { product.DocumentId = null; product.Document = null; await _productService.UpdateAsync(product); await _mediaService.DeleteAsync(document); }); }
private async Task SaveProductImages(Product product, ProductEditModel model) { var fileClient = HttpContext.RequestServices.GetRequiredService <IFileClient>(); var imageProcessor = HttpContext.RequestServices.GetRequiredService <IImageProcessor>(); await _appService.PrepareMediaAsync(product.Images, model.Images, createMedia : async(image) => { image.DirectoryName = product.SellerId.ToString(); var source = await fileClient.GetAsync(image.DirectoryName, image.FileName); if (source != null) { var(imageWidth, imageHeight) = await imageProcessor.GetImageSizeAsync(source); image.ProductId = product.Id; image.Width = imageWidth; image.Height = imageHeight; image.FileSize = source.Length; await _mediaService.CreateAsync(image); } }, updateMedia : async(image) => { await _mediaService.UpdateAsync(image); }, deleteMedia : async(image) => { await _mediaService.DeleteAsync(image); }); }
public ActionResult Edit(Int64 id) { var product = db.Products.Find(id); if (product != null) { var model = new ProductEditModel { ProductId = product.ProductId, ProductName = product.Name, BrandId = product.BrandId, SupplierId = product.SupplierId, CategoryId = product.CategoryId, Description = product.Description, IsVisible = product.IsVisible, OnSale = product.OnSale, Unit = product.Unit }; ViewBag.SupplierId = new SelectList(db.Suppliers.OrderBy(x => x.Name), "SupplierId", "Name", model.SupplierId); ViewBag.BrandId = new SelectList(db.Brands.OrderBy(x => x.Name), "BrandId", "Name", model.BrandId); ViewBag.CategoryId = new SelectList(db.Categories.OrderBy(x => x.Name), "CategoryId", "Name", model.CategoryId); return(View(model)); } else { return(RedirectToAction("Index", new { Error = "Product Not Found" })); } }
public async Task <IActionResult> Edit(ProductEditModel model) { if (ModelState.IsValid) { var seller = await HttpContext.GetMemberAsync(); var product = await _productService.GetAsync(new ProductFilter() { SellerId = seller.Id, ProductId = model.Id }); if (product != null) { await _appService.PrepareProductAsync(product, model); product.SellerId = seller.Id; await _productService.UpdateAsync(product); await SaveProductImages(product, model); await SaveProductDocument(product, model); await SaveProductTags(product, model); TempData.AddAlert(AlertMode.Notify, AlertType.Success, $"\"{product.Name}\" product was updated."); } } return(RedirectToAction(nameof(Index))); }
public ActionResult Edit(int id, ProductEditModel itemRaw) { if (ModelState.IsValid) { try { var itemDto = new ProductDTO { Id = id, Name = itemRaw.Name, Price = itemRaw.Price, }; DiscountCardService.Update(itemDto); return(RedirectToAction("Index")); } catch (ValidationException ex) { ModelState.AddModelError(ex.Property, ex.Message); } } return(View(itemRaw)); }
public ActionResult Edit(ProductEditModel model) { if (ModelState.IsValid) { var prd = _db.Products.Find(model.ProductId); var existingFile = System.IO.Path.Combine(Server.MapPath("Images"), "Products", prd.Image); if (System.IO.File.Exists(existingFile)) { System.IO.File.Delete(System.IO.Path.Combine(Server.MapPath("Images"), "Products", prd.Image)); } var fileName = string.Empty; if (model.Image != null && model.Image.ContentType.StartsWith("Image", StringComparison.OrdinalIgnoreCase)) { fileName = Guid.NewGuid().ToString(); fileName += model.Image.FileName.Substring(model.Image.FileName.LastIndexOf(".")); var fullName = System.IO.Path.Combine(Server.MapPath("~/Images"), "Products", fileName); model.Image.SaveAs(fullName); } prd.Image = fileName; prd.Name = model.ProductName; prd.Description = model.Description; prd.IsUsed = model.IsUsed; prd.Price = model.Price; prd.ExpiryDate = model.ExpiryDate; _db.SaveChanges(); return(RedirectToAction("Index")); } return(View(model)); }
public IActionResult Edit() { var model = new ProductEditModel(); model.Name = "test"; return(View(model)); }
private static Product ConvertEditModelToModel(ProductEditModel model, Category category) { return(new Product { Name = model.Name, FriendlyUrl = model.FriendlyUrl, MetaTitle = model.MetaTitle, MetaDescription = model.MetaDescription, MetaKeyWords = model.MetaKeyWords, Category = category, Price = model.Price, Manufacturer = model.Manufacturer, ManufacturerPartNumber = model.ManufacturerPartNumber, AllowCustomerComments = model.AllowCustomerComments, AllowCustomerReviews = model.AllowCustomerReviews, AllowCustomerRating = model.AllowCustomerRating, CreatedOnUtc = DateTime.UtcNow, UpdatedOnUtc = DateTime.UtcNow, Description = model.Description, Height = model.Height, Published = model.Published, Length = model.Length, ProductCost = model.ProductCost, Quantity = model.Quantity, Sku = model.Sku, Weight = model.Weight, Width = model.Width, }); }
//Edit an existing product public async Task <string> Edit(string productId, ProductEditModel data) { if (data.Name == null || data.Description == null || data.Price < 0) { throw new ArgumentException(ErrorMessages.InvalidProductParameters); } if (!this.db.Products.Any(p => p.Id == productId)) { throw new ArgumentException(ErrorMessages.InvalidProductId); } Product product = await this.db.Products.FindAsync(productId); product.Name = data.Name; product.Description = data.Description; product.Price = data.Price; product.IsTopSeller = data.IsTopSeller; product.IsNewProduct = data.IsNewProduct; product.IsBlocked = data.IsBlocked; await this.db.SaveChangesAsync(); await DeleteImages(productId); await CreateImages(data.ImageUrls, productId); await UpdateCategories(data.Categories, product.Id); await UpdateSubcategories(data.Subcategories, product.Id); return(product.Id); }
public ActionResult Add() { var newProduct = new ProductEditModel(); this.PutCategoriesInTheViewDictionary(newProduct); return(this.View(newProduct)); }
public ActionResult Add(ProductEditModel model) { var category = this.ShopData.Categories.Find(model.Category.Id); if (category == null) { this.ModelState.AddModelError(string.Empty, string.Format("You must add a valid category!")); return(this.View(model)); } var newPorduct = ConvertEditModelToModel(model, category); this.CheckForDuplicateFriendlyUrlAndName(model); if (this.ModelState.IsValid) { var savedProduct = this.ShopData.Products.Add(newPorduct); this.ShopData.SaveChanges(); this.ImageUploader.UploadImages(this.Request, this.Server, savedProduct.Images); this.ShopData.SaveChanges(); this.ClearCache(); return(this.RedirectToAction("Index")); } return(this.View(model)); }
public IActionResult ProductEdit(int?id) { if (id == null) { return(NotFound()); } var product = _productService.GetProductDetails((int)id); if (product == null) { return(NotFound()); } var model = new ProductEditModel() { ProductId = product.ProductId, categoryId = Convert.ToString(product.CategoryId), Description = product.Description, isHomePage = product.IsHomePage, isOnSale = product.IsOnSale, Price = (double)product.Price, Stock = product.Stock, Title = product.Title, imageUrl = product.Images[0].ImageUrl }; ViewBag.Categories = _categoryService.GetAllCategories(); return(View(model)); }
private void CheckForDuplicateFriendlyUrlAndName(ProductEditModel model) { if (this.ShopData.Products.All().Any(c => c.FriendlyUrl == model.FriendlyUrl || c.Name == model.Name)) { this.ModelState.AddModelError(string.Empty, string.Format("Seo Friendly Url & Name must be unique!")); } }
public ActionResult Edit(ProductEditModel model) { var product = this.ShopData.Products.Find(model.Id); if ( this.ShopData.Products.All() .Where(c => c.Id != model.Id) .Any(c => c.FriendlyUrl == model.FriendlyUrl || c.Name == model.Name)) { this.ModelState.AddModelError(string.Empty, string.Format("Seo Friendly Url & Name must be unique!")); } var category = this.ShopData.Categories.Find(model.Category.Id); if (category != null) { product.Category = category; } this.TryUpdateModel(product); if (this.ModelState.IsValid) { this.ImageUploader.UploadImages(this.Request, this.Server, product.Images); this.ShopData.SaveChanges(); this.ClearCache(); return(this.RedirectToAction("Index", "Products")); } this.PutCategoriesInTheViewDictionary(model); return(this.View(model)); }
public IActionResult ProductEdit(ProductEditModel editProduct) { if (!ModelState.IsValid) { var tempProduct = _productService.GetProductDetails(editProduct.ProductId); editProduct.imageUrl = tempProduct.Images[0].ImageUrl; ViewBag.Categories = _categoryService.GetAllCategories(); return(View(editProduct)); } var product = _productService.GetById(editProduct.ProductId); if (product == null) { return(NotFound()); } product.Description = editProduct.Description; product.CategoryId = Convert.ToInt32(editProduct.categoryId); product.IsHomePage = editProduct.isHomePage; product.IsOnSale = editProduct.isOnSale; product.Stock = editProduct.Stock; product.Price = editProduct.Price; product.Title = editProduct.Title; _productService.Update(product); return(Redirect("/admin/ProductList")); }
public ActionResult Create(ProductEditModel model) { if (db.Product.Any(p => p.ProductKey.Equals(model.Product.ProductKey))) { ModelState.AddModelError("", "Product must have a unique key."); } ValidateProduct(model.Product); if (ModelState.IsValid) { try { db.Product.Add(model.Product); db.SaveChanges(); return(RedirectToAction("Index")); } catch (DbUpdateException dbex) { var ex = (SqlException)dbex.InnerException.InnerException; foreach (SqlError error in ex.Errors) { if (error.Number == 50000) { ModelState.AddModelError("", error.Message); } } } } model.CategorySelectList = new CategoriesController().GetCategorySelectLists(model.Product.CategoryID); ViewBag.ManufacturerID = new SelectList(db.Manufacturer.OrderBy(m => m.ManufacturerName), "ManufacturerID", "ManufacturerName", model.Product.ManufacturerID); ViewBag.PhaseID = new SelectList(db.Phase.OrderBy(p => p.PhaseName), "PhaseID", "PhaseName", model.Product.PhaseID); return(View(model)); }
public ActionResult UpdateProduct(ProductEditModel model) { var response = model.Id == 0 ? _productService.AddProduct(model) : _productService.EditProduct(model); return(Json(response)); }
public static Product AsProduct(this ProductEditModel model) { return(new Product { Id = model.Id, Name = model.Name, Price = model.Price }); }
public IActionResult FormAndQuery() { var model = new ProductEditModel() { Name = "Dien ten", Rate = 5, Rating = 5, Email = "linh@linh", Id = 11 }; return(View(model)); }
public async Task <IActionResult> Edit(string id, [FromBody] ProductEditModel product) { return(await this.Execute(true, true, async() => { await this.products.Edit(id, product); return this.Ok(new { productId = id }); })); }
public ActionResult Edit(int id) { ProductManager <Product> productManager = new ProductManager <Product>(new ProductStore <Product>()); Product p = productManager.GetProductByID(id); ProductEditModel ProductModel = AutoMapper.Mapper.Map <ProductEditModel>(p); return(View(ProductModel)); }
// GET: Products/Create public ActionResult Create() { var item = new ProductEditModel { Name = "", Price = 0, }; return(View(item)); }
public IActionResult NoModelBinding() { var model = new ProductEditModel() { Name = "Dien ten", Rate = 5, Rating = 5 }; return(View(model)); }
public async Task <IActionResult> Add() { var seller = await HttpContext.GetMemberAsync(); var model = new ProductEditModel(); await _appService.PrepareModelAsync(model, null, seller); return(View(nameof(Edit), model)); }
public ActionResult Edit(ProductEditModel model) { if (ModelState.IsValid) { Product product = model.AsProduct(); repository.Update(product); return RedirectToAction("Index"); } return View(model); }
public ActionResult Edit(ProductEditModel product) { Product currentProduct = productRepository.Find(product.Id); if (currentProduct == null) { return RedirectToAction("index", "error", new { statusCode = 404 }); } var entity = product.ToEntity(currentProduct).MarkAsEdited(); productRepository.Update(entity); using (UnitOfWork) { UnitOfWork.Commit(); } return RedirectToAction("details", new { category = currentProduct.CategoryName, name = currentProduct.Name }); }
private void PopulateProduct(ProductEditModel model, Product product) { if (model.SupplierId != null) { product.Supplier = supplierRepository.Get(model.SupplierId.Value); } if (model.CategoryId != null) { product.Category = categoryRepository.Get(model.CategoryId.Value); } }