public async Task <IActionResult> EditProperties(int id, [Bind("Id, Properties")] ToursExtViewModel tour) { if (id != tour.Id) { return(NotFound()); } List <PropertyValuesModel> oldPropertieValues = await _context.PropertyValues.Where(p => p.TourId == id).ToListAsync(); if (oldPropertieValues.Count != 0) { foreach (var item in tour.Properties) { if (item.IsChecked) { if (oldPropertieValues.FirstOrDefault(pv => pv.PropertyId == item.Id && pv.TourId == tour.Id) == null) { _context.Update(new PropertyValuesModel { PropertyId = item.Id, TourId = tour.Id }); } } else { if (oldPropertieValues.FirstOrDefault(pv => pv.PropertyId == item.Id && pv.TourId == tour.Id) != null) { _context.Remove(oldPropertieValues.First(pv => pv.PropertyId == item.Id && pv.TourId == tour.Id)); } } } } else { foreach (var item in tour.Properties) { if (item.IsChecked) { _context.Update(new PropertyValuesModel { PropertyId = item.Id, TourId = tour.Id }); } } } await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); }
public async Task <IActionResult> EditProperties(int?id) { if (id == null) { return(NotFound()); } var toursModel = await _context.Tours.FindAsync(id); List <PropertiesModel> properties = await _context.Properties.ToListAsync(); List <PropertyValuesModel> propertieValues = await _context.PropertyValues.Where(p => p.TourId == id).ToListAsync(); if (propertieValues.Count != 0) { foreach (PropertiesModel p in properties) { if (propertieValues.FirstOrDefault(pv => pv.PropertyId == p.Id) != null) { p.IsChecked = true; } } } ToursExtViewModel tour = new ToursExtViewModel { Id = toursModel.Id, Title = toursModel.Title, Properties = properties, }; if (toursModel == null) { return(NotFound()); } return(View(tour)); }