Exemplo n.º 1
0
        public ActionResult Edit(DishRegister model)
        {
            if (!ModelState.IsValid)
            {
                model.selectedItems    = new MultiSelectList(db.Type, "IdType", "Name", model.dish.Type.Select(t => t.IdType));
                model.restaurant       = db.Restaurant.Find(model.idRestaurant);
                model.photos           = db.Photo.ToList().Where(m => m.Dish.Any(n => n.IdDish == model.dish.IdDish));
                model.deletedFilesIds  = "";
                model.uploadFilesNames = "";
                return(View(model));
            }
            if (model.restTypesId != null && model.restTypesId.Any())
            {
                String typeList = "";
                foreach (var typeId in model.restTypesId)
                {
                    typeList += typeId + ",";
                }
                db.PR_UpdateDishTypes(model.dish.IdDish, typeList.Remove(typeList.Length - 1));
            }
            else
            {
                db.PR_DeleteDishTypes(model.dish.IdDish);
            }

            Dish dish = db.Dish.Find(model.dish.IdDish);

            dish.Name            = model.dish.Name;
            dish.Description     = model.dish.Description;
            dish.Price           = model.dish.Price;
            db.Entry(dish).State = EntityState.Modified;

            if (model.deletedFilesIds != null)
            {
                foreach (var idPhotoDelete in model.deletedFilesIds.Split(','))
                {
                    db.PR_DeleteDishPhoto(dish.IdDish, int.Parse(idPhotoDelete));
                }
            }

            if (model.uploadFilesNames != null)
            {
                string[] uploadFiles = model.uploadFilesNames.Split(',');
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    HttpPostedFileBase tmpFile = Request.Files[i];
                    if (tmpFile != null && uploadFiles.Any(name => name == tmpFile.FileName) &&
                        uploadFiles.Length > 0)
                    {
                        byte[] dbImage  = FileUpload(tmpFile);
                        Photo  tmpPhoto = new Photo();
                        tmpPhoto.Photo1 = dbImage;
                        db.Photo.Add(tmpPhoto);

                        dish.Photo.Add(tmpPhoto);
                        tmpPhoto.Dish.Add(dish);
                        uploadFiles = uploadFiles.Where(name => name != tmpFile.FileName).ToArray();
                    }
                }
            }

            db.SaveChanges();
            TempData["Success"] = dish.Name + " edited successfully.";
            return(RedirectToAction("Index", "Locals", new { id = dish.IdRestaurant }));
        }