Exemplo n.º 1
0
        public ActionResult Edit(RestaurantViewModel viewModel)
        {
            if (viewModel == null)
            {
                // this should not be possible, but just in case, validate
                TempData["ErrorMessage"] = "Ups, a serious error occured: No Viewmodel.";
                return(RedirectToAction("Index"));
            }

            // get the item from the database by ID
            UnitOfWork unitOfWork   = new UnitOfWork();
            Restaurant dbRestaurant = unitOfWork.RestaurantRepository.GetByID(viewModel.ID);

            // if there is no object in the DB, this is a new item -> will create a new one
            if (dbRestaurant == null)
            {
                dbRestaurant             = new Restaurant();
                dbRestaurant.DateCreated = DateTime.Now;
            }

            // update the DB object from the viewModel
            viewModel.UpdateDbModel(dbRestaurant);

            // save the image to the local folder if there is an uploaded image
            // we have to generate a unique file name, to avoid duplication when the same image is uploaded for another restaurant
            if (Request.Files.Count > 0)
            {
                HttpPostedFileBase file = Request.Files[0];
                // check if the uploaded file is a valid file and only then proceed
                if (file.ContentLength > 0 && string.IsNullOrEmpty(file.FileName) == false)
                {
                    string imagesPath     = Server.MapPath(Constants.ImagesDirectory);
                    string uniqueFileName = string.Format("{0}_{1}", DateTime.Now.Ticks, file.FileName);
                    string savedFileName  = Path.Combine(imagesPath, Path.GetFileName(uniqueFileName));
                    file.SaveAs(savedFileName);
                    dbRestaurant.ImageName = uniqueFileName;
                }
            }

            unitOfWork.RestaurantRepository.Save(dbRestaurant);
            unitOfWork.Save();

            TempData["Message"] = "The restaurant was saved successfully";
            return(RedirectToAction("Index"));
        }