public ActionResult Edit(PosadasViewModel posadaViewModel) { if (ModelState.IsValid) { var posada = Mapper.Map <PosadasViewModel, Posada>(posadaViewModel); if (posadaViewModel.LugarId == -1) { posada.LugarId = null; posada.Misc = posadaViewModel.OtroLugar; } //store in the viewModel? var oldCaracteristicas = unitOfWork.CaracteristicasPosadasRepository.Get(p => p.PosadaId == posada.Id).ToList(); //posada.Caracteristicas = oldCaracteristicas; if (posadaViewModel.CaracteristicasId == null) { posadaViewModel.CaracteristicasId = new int[0]; } var remove = oldCaracteristicas.Where(x => !posadaViewModel.CaracteristicasId.Contains(x.CaracteristicaId)).ToList(); unitOfWork.CaracteristicasPosadasRepository.Delete(remove); var addIds = posadaViewModel.CaracteristicasId.Where(x => !oldCaracteristicas.Select(c => c.CaracteristicaId).Contains(x)).ToArray(); foreach (var caracteristicaId in addIds) { unitOfWork.CaracteristicasPosadasRepository.Insert(new CaracteristicasPosadas() { PosadaId = posada.Id, CaracteristicaId = caracteristicaId }); } unitOfWork.PosadaRepository.Update(posada); unitOfWork.Save(); return(RedirectToAction("Index")); } return(View(posadaViewModel)); }
public ActionResult Create(PosadasViewModel posadaViewModel) { if (ModelState.IsValid) { var posada = Mapper.Map <PosadasViewModel, Posada>(posadaViewModel); posada.UserId = User.Identity.GetUserId(); posada.Caracteristicas = new List <CaracteristicasPosadas>(); if (posadaViewModel.CaracteristicasId != null) { foreach (var caracteristicaId in posadaViewModel.CaracteristicasId) { posada.Caracteristicas.Add(new CaracteristicasPosadas() { CaracteristicaId = caracteristicaId }); } } if (posada.LugarId == -1)//Seleccionaron otro { posada.LugarId = null; posada.Misc = posadaViewModel.OtroLugar; } unitOfWork.PosadaRepository.Insert(posada); unitOfWork.Save(); var root = Server.MapPath(Constantes.PosadasBase + posada.Id + "/"); var fotosList = new List <FotosPosada>(); foreach (var item in posadaViewModel.FotosModels) { if (item.FileBase == null) { continue; } string ext = Path.GetExtension(item.FileBase.FileName); string filename = "Posada-" + posada.Id + "-" + Guid.NewGuid() + ext; var uploadResult = CloudinaryService.UploadFile(filename, item.FileBase.InputStream, "Posada-" + posada.Id, "FotosPosadas"); var fotoPosada = new FotosPosada { Alt = item.Alt, PosadaId = posada.Id, Ruta = uploadResult.Url, ImagenPublicId = uploadResult.PublicId, ImageServer = uploadResult.Server }; //fotoPosada.Ruta = Guid.NewGuid() + ext; //Directory.CreateDirectory(root); //item.FileBase.SaveAs(root + fotoPosada.Ruta); fotosList.Add(fotoPosada); } unitOfWork.FotosPosadaRepository.Insert(fotosList); unitOfWork.Save(); return(RedirectToAction("Details", new { id = posada.Id })); } return(View(posadaViewModel)); }