public async Task <IActionResult> Create() { var viewModel = new SneakersCreateViewModel { AvailableBrands = await _context.Brand.ToListAsync(), AvailableConditions = await _context.Condition.ToListAsync(), AvailableSizes = await _context.Size.ToListAsync() }; return(View(viewModel)); }
public async Task <IActionResult> Create(SneakersCreateViewModel viewModel) { ModelState.Remove("Sneaker.Brand"); ModelState.Remove("Sneaker.Condition"); ModelState.Remove("Sneaker.Size"); ModelState.Remove("Sneaker.User"); ModelState.Remove("Sneaker.UserId"); // If the Photo property on the incoming model object is not null, then the user // has selected an image to upload. if (ModelState.IsValid) { string uniqueFileName = null; // If the Photo property on the incoming model object is not null, then the user // has selected an image to upload. if (viewModel.Photo != null) { // The image must be uploaded to the images folder in wwwroot // To get the path of the wwwroot folder we are using the inject // HostingEnvironment service provided by ASP.NET Core string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images"); // To make sure the file name is unique we are appending a new // GUID value and and an underscore to the file name uniqueFileName = Guid.NewGuid().ToString() + "_" + viewModel.Photo.FileName; string filePath = Path.Combine(uploadsFolder, uniqueFileName); // Use CopyTo() method provided by IFormFile interface to // copy the file to wwwroot/images folder viewModel.Photo.CopyTo(new FileStream(filePath, FileMode.Create)); } var sneaker = viewModel.Sneaker; var currUser = await GetCurrentUserAsync(); sneaker.ImgPath = uniqueFileName; sneaker.UserId = currUser.Id; _context.Add(sneaker); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } viewModel.AvailableBrands = await _context.Brand.ToListAsync(); viewModel.AvailableConditions = await _context.Condition.ToListAsync(); viewModel.AvailableSizes = await _context.Size.ToListAsync(); return(View(viewModel)); }