public ActionResult AddNew(HurricaneViewModel NewHurricane) { if (ModelState.IsValid) { Hurricane newHurricane = (Hurricane)NewHurricane; newHurricane.AffectedCounties.Clear(); _context.Hurricanes.Add(newHurricane); foreach (int countyId in NewHurricane.AffectedCountiesId) { newHurricane.AffectedCounties.Add(_context.Counties.Find(countyId)); } _context.SaveChanges(); return(RedirectToAction("Index")); } else { IEnumerable <CountyViewModel> availableCounties = _context.Counties .ToArray() .Select(county => (CountyViewModel)county) .ToArray(); HurricanesIndexViewModel viewModel = new HurricanesIndexViewModel(availableCounties) { Hurricanes = _context.Hurricanes .Include(h => h.AffectedCounties) .ToArray() .Select(h => (HurricaneViewModel)h) .ToArray(), NewHurricane = NewHurricane }; return(View("Index", viewModel)); } }
public ActionResult Index() { IEnumerable <CountyViewModel> availableCounties = _context.Counties .ToArray() .Select(county => (CountyViewModel)county) .ToArray(); HurricanesIndexViewModel viewModel = new HurricanesIndexViewModel(availableCounties) { Hurricanes = _context.Hurricanes .Include(h => h.AffectedCounties) .ToArray() .Select(h => (HurricaneViewModel)h) .ToArray(), NewHurricane = new HurricaneViewModel() }; return(View(viewModel)); }