// Save images from AddPokemon model private string[] UploadedPokemonImages(AddPokemon model) { string[] imageUrls = new string[2]; if (model.UploadImage != null || model.UploadShinyImage != null) { string uploadsFolder = Path.Combine(webEnvironment.WebRootPath, "images/pokemon"); if (model.UploadImage != null) { imageUrls[0] = "uploaded" + Guid.NewGuid().ToString() + "_" + model.UploadImage.FileName; string imagePath = Path.Combine(uploadsFolder, imageUrls[0]); using (var fileStream = new FileStream(imagePath, FileMode.Create)) { model.UploadImage.CopyTo(fileStream); } } if (model.UploadShinyImage != null) { imageUrls[1] = "uploaded" + Guid.NewGuid().ToString() + "_" + model.UploadShinyImage.FileName; string shinyImagePath = Path.Combine(uploadsFolder, imageUrls[1]); using (var fileStream = new FileStream(shinyImagePath, FileMode.Create)) { model.UploadShinyImage.CopyTo(fileStream); } } } return(imageUrls); }
public async Task <IActionResult> AddPokemon(AddPokemon model) { if (ModelState.IsValid) { try { string[] imageUrls = UploadedPokemonImages(model); string standardUrl = imageUrls[0]; string shinyImageUrl = imageUrls[1]; Pokemon newPokemon = new Pokemon { PokemonName = model.PokemonName, PokedexNum = model.PokedexNum, Type_1 = model.Type_1, Type_2 = model.Type_2, Classification = model.Classification, Description = model.Description, Height = model.Height, Weight = model.Weight, Generation = model.Generation, Image = standardUrl, ShinyImage = shinyImageUrl, Rarity = model.Rarity }; _context.Add(newPokemon); _context.SaveChanges(); List <AreasPokemon> newListOfAreas = new List <AreasPokemon>(); if (model.AreaIds != null) { foreach (int areaId in model.AreaIds) { newListOfAreas.Add(new AreasPokemon { AreaId = areaId, PokemonId = newPokemon.PokemonId }); } foreach (AreasPokemon area in newListOfAreas) { _context.Add(area); _context.SaveChanges(); } } return(RedirectToAction("Pokemon", "Admin")); } catch (Exception) { ModelState.AddModelError("Custom", "Pokémon Name or Number already exists!"); ViewData["Types"] = await _context.Pokemon.Select(p => p.Type_1).Distinct().ToListAsync(); ViewData["Areas"] = await _context.Areas.ToListAsync(); return(View(model)); } } ViewData["Types"] = await _context.Pokemon.Select(p => p.Type_1).Distinct().ToListAsync(); ViewData["Areas"] = await _context.Areas.ToListAsync(); return(View(model)); }