public async Task <IActionResult> Add() { ViewData["enemies"] = await GetVillainNamesAsync(); var viewModel = new SuperheroAddViewModel(); return(View(viewModel)); }
public async Task <IActionResult> Add(SuperheroAddViewModel viewModel) { if (ModelState.IsValid) { try { var model = new Superhero(); model.AssetsValue = viewModel.AssetsValue; model.CanFly = viewModel.CanFly; model.HeroName = viewModel.HeroName; model.Powers = viewModel.Powers; model.SecretName = viewModel.SecretName; model.Strength = viewModel.Strength; if (viewModel.EnemiesIds != null) { model.Enemies = new List <Villain>(); foreach (var enemyId in viewModel.EnemiesIds) { var villain = await _context.Villains.FirstOrDefaultAsync(x => x.Id == enemyId); model.Enemies.Add(villain); } } _context.Superheroes.Add(model); await _context.SaveChangesAsync(); TempData["MessageText"] = "Superhero successfully updated!"; TempData["MessageSeverity"] = MessageSeverity.Ok; } catch (NotFoundException) { TempData["MessageText"] = "Superhero not found!"; TempData["MessageSeverity"] = MessageSeverity.Error; } return(RedirectToAction(nameof(Index))); } else { ViewData["enemies"] = await GetVillainNamesAsync(); return(View(viewModel)); } }