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)); }
public async Task <IActionResult> Create([Bind("Id,Name,Description,Weight,Price,WholesalePrice,Image,CategoryId,Archived,SoldOut,Quantity,Date")] Item item, IFormFile file) { if (ModelState.IsValid) { item.Date = DateTime.Now.ToString(); if (item.Name.Length > 19) { item.ShortName = item.Name.Substring(19); } else { item.ShortName = item.Name; } _context.Add(item); await _context.SaveChangesAsync(); if (file != null || file.Length != 0) { // Create a File Info FileInfo fi = new FileInfo(file.FileName); // This code creates a unique file name to prevent duplications // stored at the file location var newFilename = item.Id + "_" + String.Format("{0:d}", (DateTime.Now.Ticks / 10) % 100000000) + fi.Extension; var webPath = _hostingEnvironment.WebRootPath; var path = Path.Combine("", webPath + @"\ImageFiles\" + newFilename); // IMPORTANT: The pathToSave variable will be save on the column in the database var pathToSave = @"/ImageFiles/" + newFilename; // This stream the physical file to the allocate wwwroot/ImageFiles folder using (var stream = new FileStream(path, FileMode.Create)) { await file.CopyToAsync(stream); } // This save the path to the record item.ImagePath = pathToSave; _context.Update(item); await _context.SaveChangesAsync(); } return(RedirectToAction(nameof(Index))); } ViewData["CategoryId"] = new SelectList(_context.Set <Category>(), "Id", "Name", item.CategoryId); return(View(item)); }