public IActionResult Edit(int?id) { if (id == null) { return(NotFound()); } var product = _productRepository.GetById(id); if (product == null) { return(NotFound()); } PopulateDropdownList(product.CategoryId); var pvm = new ProductCreateViewModel(); pvm.ProductList = _productRepository.GetAll(); pvm.Name = product.Name; pvm.Price = product.Price; pvm.ExpireDate = product.ExpireDate; pvm.IsActive = product.IsActive; pvm.Category = product.Category; pvm.CategoryId = product.CategoryId; return(View("Create", pvm)); }
private async Task ProductCreate() { for (int i = 1; i <= 100; i++) { var product = new ProductCreateViewModel { Name = $"SomeProductName{i}", ProductInformation = new ProductInformationViewModel { ScreenSize = "15", Memory = 128, NumberOfCores = 2, Ram = 4, OperatingSystem = "Android" }, Price = Rnd(100, 2000), ProviderId = _applicationContext.Providers .FirstOrDefault(w => string.Equals(w.Name, $"SomeProviderName{Rnd(1,11)}", StringComparison.InvariantCultureIgnoreCase)).Id, Description = $"SomeDescription By Product{i}", UrlImage = "https://content2.onliner.by/catalog/device/main/febab87ed7324e7912223b66e425b72a.jpeg" }; await _productService.Create(product); } }
public void CreateReturnsRedirectToActionResult() { var productsController = InitializeProductsController(); using (var stream = new MemoryStream(new byte[] { 1, 2, 3, 4 })) { var file = new Mock <IFormFile>(); file.Setup(f => f.FileName) .Returns("test.jpg") .Verifiable(); file.Setup(f => f.CopyToAsync(It.IsAny <Stream>(), CancellationToken.None)) .Callback <Stream, CancellationToken>((stream, token) => { stream.CopyTo(stream); }).Returns(Task.CompletedTask); var productCreateViewModel = new ProductCreateViewModel { Name = "test", CategoryId = 3, Image = file.Object, }; var result = productsController.Create(productCreateViewModel); var viewResult = Assert.IsType <RedirectToActionResult>(result); Assert.True(viewResult.ActionName.Equals("Index")); } }
public async Task <IActionResult> Create(ProductCreateViewModel entity, IFormFile Image) { if (ModelState.IsValid) { Product product = new Product() { Name = entity.Name, Quantity = entity.Quantity, Code = entity.Code, Price = entity.Price, CategoryId = entity.CategoryId }; if (Image.Length > 0) { using (MemoryStream stream = new MemoryStream()) { await Image.CopyToAsync(stream); product.Image = stream.ToArray(); } } bool isSave = _productManager.Add(product); if (isSave) { return(RedirectToAction("List")); } } return(View()); }
public ActionResult Create([Bind(Include = "ProductId,ProductName,ProductCode,Remark,Description,PriceExVAT,Reprobel,Bebat,Recupel,Auvibel,PurchasePrice,Brand,CategoryId,VATPercId,Stock,EAN")] ProductCreateViewModel product) { if (ModelState.IsValid) { Product prod = new Product(); prod.ProductName = product.ProductName; prod.ProductCode = product.ProductCode; prod.Remark = product.Remark; prod.Description = product.Description; prod.PriceExVAT = product.PriceExVAT; prod.Reprobel = product.Reprobel; prod.Bebat = product.Bebat; prod.Recupel = product.Recupel; prod.Auvibel = product.Auvibel; prod.PurchasePrice = product.PurchasePrice; prod.Brand = product.Brand; prod.CategoryId = product.CategoryId; prod.VATPercId = product.VATPercId; prod.Stock = product.Stock; prod.EAN = product.EAN; prod.Active = true; db.Products.Add(prod); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(product)); }
public async Task <IActionResult> Create(ProductCreateViewModel model) { ModelState.Remove("product.User"); if (ModelState.IsValid) { long size = 0; foreach (var file in model.image) { var filename = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); filename = _environment.WebRootPath + $@"\products\{file.FileName.Split('\\').Last()}"; size += file.Length; using (var fileStream = new FileStream(filename, FileMode.Create)) { await file.CopyToAsync(fileStream); model.Product.ImgPath = $@"\products\{file.FileName.Split('\\').Last()}"; } } var user = await GetCurrentUserAsync(); model.Product.User = user; _context.Add(model.Product); await _context.SaveChangesAsync(); return(RedirectToAction("Index")); } ViewData["ProductTypeId"] = new SelectList(_context.ProductType, "ProductTypeId", "ProductTypeId", model.Product.ProductTypeId); ProductCreateViewModel model2 = new ProductCreateViewModel(_context); return(View(model2)); }
public ActionResult Create(ProductCreateViewModel model) { //var product = Mapper.Map<Product>(model); Product product = new Product() { Name = model.Name, Code = model.Code, CategoryId = model.CategoryId }; try { if (ModelState.IsValid) { productManager.Add(product); //return RedirectToAction("Index"); ViewBag.message = "Product Added Sucessfully"; } } catch (Exception ex) { ViewBag.message = ex.Message; } model.ProductCategoryLookUp = new SelectList(GetProductCategories(), "Id", "Name"); model.Products = productManager.GetAll(); return(View(model)); }
public ActionResult Create(ProductCreateViewModel createViewModel) { if (createViewModel == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } if (this.ModelState.IsValid) { using (var db = new YonkersContext()) { Producto pro = new Producto { categoriaID = createViewModel.CategoryId, yonkerID = 1, nombrepro = createViewModel.Name, precio = createViewModel.Precio, }; db.Producto.Add(pro); db.SaveChanges(); return(RedirectToAction("Index")); } } return(this.View(createViewModel)); }
public async Task <IActionResult> Create(ProductCreateViewModel viewModel) { ModelState.Remove("Product.User"); ModelState.Remove("Product.UserId"); ModelState.Remove("Product.ProductType"); var product = viewModel.product; if (ModelState.IsValid) { var currentUser = await _userManager.GetUserAsync(HttpContext.User); product.UserId = currentUser.Id; _context.Add(product); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } List <ProductType> categories = await _context.ProductType.ToListAsync(); var updated = categories.Select(c => new SelectListItem(c.Label, c.ProductTypeId.ToString())).ToList(); updated.Insert(0, new SelectListItem("Select a category", null)); viewModel.productTypes = updated; return(View(viewModel)); }
public async Task <IActionResult> Create(ProductCreateViewModel user_data) { IFormFile image = user_data.Image; var imageErrorMsg = new StringBuilder(); if (ModelState.IsValid && image.Length > 0 && (_fileHandler.CheckContentType(image, new List <string> { "image/jpg", "image/jpeg", "image/svg+xml", "image/png" }, imageErrorMsg) & _fileHandler.CheckSize(image, 2 * StorageUnits.Megabyte, imageErrorMsg))) { string imagePath = _fileHandler.Upload(image); var product = new Product { Name = user_data.Name, Price = user_data.Price, Quantity = user_data.Quantity, Image = imagePath }; await _context.AddAsync(product); _context.SaveChanges(); return(RedirectToRoute("product-index")); } ModelState.AddModelError("image", imageErrorMsg.ToString()); return(View(user_data)); }
public static ProductRequest MapToRequest(this ProductCreateViewModel model) { if (model is null) { throw new ArgumentNullException(nameof(model)); } var productRequest = new ProductRequest { ShortDescription = model.ShortDescription, LongDescription = model.LongDescription }; if (model.Image != null) { using var ms = new MemoryStream(); model.Image.CopyTo(ms); var fileBytes = ms.ToArray(); productRequest.Image = fileBytes; } else { productRequest.Image = Convert.FromBase64String(Constants.Defaults.Image); } foreach (var item in model.Categories) { productRequest.Categories.Add(new CategoryFullRequest { Id = item }); } return(productRequest); }
// GET: Products/Create public IActionResult Create() { //create an instance of the ProductCreateViewModel to get a list of ProductTypes for the dropdown ProductCreateViewModel ViewModel = new ProductCreateViewModel(); //then use the view model rather than view data for more flexibility ViewModel.productTypes = _context.ProductType.Select(c => new SelectListItem { Text = c.Label, Value = c.ProductTypeId.ToString() } ).ToList(); //forces user to choose a product category before continuing. Error message displays due to //data annotation on ProductTypeId requiring the foreign key to be greater than 0 or display //an error message. Otherwise, this will give the productType an id of 0 and try to send to database ViewModel.productTypes.Insert(0, new SelectListItem() { Value = "0", Text = "--Select Product Category--" }); //ViewData["ProductTypeId"] = new SelectList(_context.ProductType, "ProductTypeId", "Label"); //ViewData["UserId"] = new SelectList(_context.ApplicationUsers, "Id", "Id"); return(View(ViewModel)); }
public async Task <IActionResult> Create(ProductCreateViewModel model) { if (ModelState.IsValid) { var fileName = "noimage.jpg"; if (model.FileUpload != null) { var folderPath = Path.Combine(environment.WebRootPath, "images", "products"); fileName = $"{Guid.NewGuid()}_{model.FileUpload.FileName}"; var filePath = Path.Combine(folderPath, fileName); using (var fileStream = new FileStream(filePath, FileMode.Create)) { await model.FileUpload.CopyToAsync(fileStream); } } var product = new ProductViewModel() { CategoryId = model.CategoryId, Description = model.Description, FileAvatarName = fileName, ProductName = model.ProductName, QuantityPerUnit = model.QuantityPerUnit, UnitPrice = model.UnitPrice }; if (productService.Create(product)) { return(RedirectToAction("Index", "Product")); } } return(View(model)); }
public IHttpResponse Create(ProductCreateViewModel model) { if (model.Name == null || model.Description == null || model.Type == null || model.Price < 0) { return(BadRequestErrorWithView("Invalid product data!")); } var isParsed = Enum.TryParse <ProductType>(model.Type, out ProductType type); if (!isParsed) { return(BadRequestErrorWithView("Invalid product type!")); } var product = this.Db.Products.Add(new Product { Name = model.Name, Price = model.Price, Description = model.Description, Type = type }); this.Db.SaveChanges(); return(this.Redirect($"/Products/Details?id={product.Entity.Id}")); }
public IActionResult Edit(int?id) { if (id == null) { return(NotFound()); } var product = _productManager.GetById((Int64)id); PopulateDropdownList(product.CategoryId); ProductCreateViewModel productCreateViewModel = _mapper.Map <ProductCreateViewModel>(product); if (product == null) { return(NotFound()); } //var productCreateViewModel = new ProductCreateViewModel(); productCreateViewModel.ProductList = _productManager.GetAll().ToList(); //productCreateViewModel.Name = product.Name; //productCreateViewModel.Price = product.Price; //productCreateViewModel.ExpireDate = product.ExpireDate; //productCreateViewModel.IsActive = product.IsActive; //productCreateViewModel.Category = product.Category; //productCreateViewModel.CategoryId = Convert.ToInt32(product.CategoryId); //productCreateViewModel.ImageUrl = product.ImageUrl; return(View(product)); }
public ResultViewModel Post([FromBody] ProductCreateViewModel model) { model.Validate(); if (model.Invalid) { return(new ResultViewModel { Success = false, Message = "Não foi possivel cadastrar o produto", Data = model.Notifications }); } var product = new Product(); product.Title = model.Title; product.CategoryId = model.CategoryId; product.CreateDate = DateTime.Now; product.Description = model.Description; product.Image = model.Image; product.LastUpdateDate = DateTime.Now; product.Price = model.Price; product.Quantity = model.Quantity; repository.Insert(product); return(new ResultViewModel { Success = true, Message = "Produto cadastrado com sucesso", Data = product }); }
public ActionResult addNewCategoryHeader(ProductCreateViewModel pcvm) { CategoryHeaderModel category = pcvm.CategoryHeader; categoryHeaderRepository.InsertOrUpdate(category); return(Redirect(Request.UrlReferrer.ToString())); }
// HN: This is the end of the details view; To update the quantity of items shown, a product needs to be added to a valid order via the "add to order" button. This also involves a valid user and a "shopping cart" (which represents the open order). //--------------------------------------------------------------------------------------------------------------------- // GET: Products/Create // BR: When a user chooses to add a product to sell this method directs the user to the correct form view public IActionResult Create() { //BR: get product type data from the database var ProductTypeData = _context.ProductType; List <SelectListItem> ProductTypesList = new List <SelectListItem>(); //BR: include the select option in the product type list ProductTypesList.Insert(0, new SelectListItem { Text = "Select", Value = "" }); //BR: for each statement that takes each product from the database and converts it to a select list item and adds them to the product types list foreach (var pt in ProductTypeData) { SelectListItem li = new SelectListItem { Value = pt.ProductTypeId.ToString(), Text = pt.Label }; ProductTypesList.Add(li); } ; ProductCreateViewModel PCVM = new ProductCreateViewModel(); PCVM.ProductTypes = ProductTypesList; return(View(PCVM)); }
public async Task <IActionResult> Create() { var productTypes = await _context.ProductType.ToListAsync(); var productTypeListOptions = new List <SelectListItem>(); foreach (ProductType pt in productTypes) { productTypeListOptions.Add(new SelectListItem { Value = pt.ProductTypeId.ToString(), Text = pt.Label }); } ProductCreateViewModel createViewModel = new ProductCreateViewModel(); productTypeListOptions.Insert(0, new SelectListItem { Text = "Choose a Category", Value = "0" }); createViewModel.ProductTypes = productTypeListOptions; return(View(createViewModel)); }
public ViewResult Update(long Id) { var item = repository.GetById(Id); ProductCreateViewModel p = new ProductCreateViewModel() { Id = Id, Ammount = item.Ammount, Category = item.Category, Description = item.Description, Name = item.Name, Price = item.Price, Rating = item.Rating, }; string folder = Path.Combine(hostingEnvironment.WebRootPath, "images", item.Id.ToString()); try { IEnumerable <string> files = Directory.EnumerateFiles(folder); p.img = new List <string>(); foreach (var img in files) { p.img.Add(img); } } catch { } return(View(p)); }
public IActionResult Create() { ProductCreateViewModel model = new ProductCreateViewModel(); model.Brands = Brands; return(View(model)); }
public async void CanReturnProductCreate() { var options = new DbContextOptionsBuilder <ProductDbContext>() .UseInMemoryDatabase(databaseName: "testDb") .Options; var builder = new ConfigurationBuilder().AddEnvironmentVariables(); var config = builder.Build(); using (var context = new ProductDbContext(options)) { context.Product.AddRange( new Product { Name = "test1", Price = 12.99, Description = "first test item", ImagePath = "test/path", StudentSale = false }, new Product { Name = "test2", Price = 78.99, Description = "second test item", ImagePath = "test/path2", StudentSale = false }, new Product { Name = "test3", Price = 2.99, Description = "third test item", ImagePath = "test/path3", StudentSale = true, SalePrice = 1.99 } ); context.SaveChanges(); ProductCreateViewModel vm = new ProductCreateViewModel(); var controller = new ProductController(context); var result = await controller.Create(vm); Assert.IsType <RedirectToActionResult>(result); } }
// GET: Products/Create public IActionResult Create() { ProductCreateViewModel productCreateViewModel = new ProductCreateViewModel(); productCreateViewModel.CategoryList = _context.Category.ToList(); return(View(productCreateViewModel)); }
public IActionResult Create(ProductCreateViewModel model) { if (ModelState.IsValid) { var product = new Product() { ProductName = model.ProductName, BrandId = model.BrandId, Stock = model.Stock, Description = model.Description, Price = model.Price, CategoryId = model.CategoryId, IsDelete = false }; var fileName = string.Empty; if (model.Image != null) { string uploadFolder = Path.Combine(webHostEnvironment.WebRootPath, "images/Product"); fileName = $"{Guid.NewGuid()}_{model.Image.FileName}"; var filePath = Path.Combine(uploadFolder, fileName); using (var fs = new FileStream(filePath, FileMode.Create)) { model.Image.CopyTo(fs); } } product.PathImage = fileName; productRepository.Create(product); return(RedirectToAction("Index", "Home")); } return(View()); }
public async Task <IActionResult> Create(Product product) { // Remove the user from the model validation because it is // not information posted in the form ModelState.Remove("product.User"); if (ModelState.IsValid) { /* * If all other properties validation, then grab the * currently authenticated user and assign it to the * product before adding it to the db _context */ var user = await GetCurrentUserAsync(); product.User = user; _context.Add(product); await _context.SaveChangesAsync(); return(RedirectToAction("Index")); } ProductCreateViewModel model = new ProductCreateViewModel(_context); return(View(model)); }
public ActionResult Create(ProductCreateViewModel model) { try { // TODO: Add insert logic here if (model.File.Length > 0) { var filePath = Path.Combine(environment.WebRootPath, @"Images", model.File.FileName); var x = Path.Combine(Directory.GetCurrentDirectory(), @"Images"); using (var stream = new FileStream(filePath, FileMode.Create)) { model.File.CopyToAsync(stream); model.Product.ImagePath = model.File.FileName; } } try { productRepository.Create(model.Product); } catch (Exception ex) { } return(RedirectToAction(nameof(Index))); } catch (Exception ex) { return(View()); } }
public async Task <IActionResult> Create([Bind("ProductId,DateCreated,Description,Title,Price,Quantity,UserId,City,ImagePath,Active,ProductTypeId")] Product product) { //should I be getting the true user id, because that's what i am getting?? ModelState.Remove("product.User"); ModelState.Remove("product.UserId"); ProductCreateViewModel ViewModel = new ProductCreateViewModel(); if (ModelState.IsValid) { //User checks id var user = await GetCurrentUserAsync(); product.UserId = user.Id; _context.Add(product); await _context.SaveChangesAsync(); return(RedirectToAction("Details", new { id = product.ProductId })); } ViewModel.productTypes = _context.ProductType.Select(c => new SelectListItem { Text = c.Label, Value = c.ProductTypeId.ToString() }).ToList(); //ViewData["ProductTypeId"] = new SelectList(_context.ProductType, "ProductTypeId", "Label", product.ProductTypeId); //ViewData["UserId"] = new SelectList(_context.ApplicationUsers, "Id", "Id", product.UserId); return(View(ViewModel)); }
public async Task <IActionResult> Create( [Bind("Name", "Price", "Description", "ImagePath")] ProductCreateViewModel vm) { if (!ModelState.IsValid) { return(View(vm)); } Product product = new Product() { Name = vm.Name, Price = vm.Price, Description = vm.Description, ImagePath = vm.ImagePath }; await _context.Product.AddAsync(product); try { await _context.SaveChangesAsync(); } catch { return(View(vm)); } return(RedirectToAction("Details", new { product.Id })); }
public ActionResult Create(int?catId) { if (GetVendorProductsCount() >= GetMaxProductsAllowed()) { return(View("Error")); } if (catId == null) { return(RedirectToAction("Index", controllerName: "Store")); } TempData["catId"] = catId; var parent = db.Categories.Include(m => m.Attributes).FirstOrDefault(m => m.Id == catId); var model = new ProductCreateViewModel { Specifications = new Dictionary <string, string>(), IsActive = true, DefaultGST = parent.DefaultGST, CategoryName = parent.Name }; model.Attributes = new Dictionary <string, int>(); while (parent != null) { foreach (var atr in parent.Attributes.Reverse()) { model.Attributes.Add(atr.Name, atr.Id); model.Specifications.Add(atr.Name, atr.Default); } parent = db.Categories.Include(m => m.Attributes).FirstOrDefault(m => m.Id == parent.CategoryId); } model.AttributeNames = model.Attributes.Keys.ToList(); model.AttributeNames.Reverse(); return(View(model)); }
public IActionResult Create(ProductCreateViewModel model) { if (ModelState.IsValid) { var product = new Product() { Name = model.Name, Price = model.Price, ExpireDate = model.ExpireDate, IsActive = model.IsActive, CategoryId = model.CategoryId }; bool isAdded = _productRepository.Add(product); if (isAdded) { ViewBag.SuccessMessage = "Saved Successfully!"; } } else { ViewBag.ErrorMessage = "Operation Failed!"; } model.ProductList = _productRepository.GetAll(); PopulateDropdownList(model.CategoryId); /*Dropdown List Binding*/ return(View(model)); }