public ActionResult Edit(CreateMealViewModel viewModel) { HttpPostedFileBase hpf = Request.Files[0] as HttpPostedFileBase; if (ModelState.IsValid) { Meal meal = mealRepo.GetSingleEntity(x => x.MealId == viewModel.MealId); meal.CategoryId = viewModel.CategoryId; meal.MealName = viewModel.MealName; meal.Price = viewModel.Price; if (hpf != null && hpf.ContentLength != 0) { string savedFileName = Guid.NewGuid().ToString() + "." + (hpf.FileName.Split('.')).Last(); string path = Path.Combine(Server.MapPath("~/Content/ProductImg"), savedFileName); hpf.SaveAs(path); meal.Image = savedFileName; } mealRepo.Update(meal); mealRepo.SaveChanges(); return(RedirectToAction("Index")); } viewModel.Categories = categoryRepo.GetWithFilterAndOrder(); return(View(viewModel)); }
public async Task <IActionResult> AddMeal([FromBody] CreateMealViewModel viewModel) { if (!ModelState.IsValid) { return(BadRequest()); } var meal = mapper.Map <CreateMealViewModel, Meal>(viewModel); var userId = userService.GetCurrentUserId(HttpContext); meal.UserID = userId; var response = await mealService.Create(meal).ConfigureAwait(false); if (!response.IsSuccess) { return(BadRequest(response.Message)); } var userMealsResponse = await mealService.GetUserMeals(userId).ConfigureAwait(false); if (!userMealsResponse.IsSuccess) { return(BadRequest(userMealsResponse.Message)); } var userMealsViewModel = mapper.Map <IEnumerable <Meal>, IEnumerable <MealViewModel> >(userMealsResponse.MealsFound); return(Ok(userMealsViewModel)); }
public async Task <IActionResult> Create(CreateMealInputModel inputModel) { var viewModel = new CreateMealViewModel(); if (!this.ModelState.IsValid) { viewModel.CategoriesItems = this.categoriesService.GetAllCategories(); return(this.View(viewModel)); } var user = await this.userManager.GetUserAsync(this.User); try { await this.mealService.CreateAsync(inputModel, user.Id, $"{this.environment.WebRootPath}/images"); } catch (Exception exception) { this.ModelState.AddModelError(string.Empty, exception.Message); viewModel.CategoriesItems = this.categoriesService.GetAllCategories(); return(this.View(viewModel)); } return(this.RedirectToAction(nameof(this.All))); }
public IActionResult Create() { var viewModel = new CreateMealViewModel(); viewModel.CategoriesItems = this.categoriesService.GetAllCategories(); return(this.View(viewModel)); }
public ActionResult Create() { var viewModel = new CreateMealViewModel() { Categories = categoryRepo.GetWithFilterAndOrder() }; return(View(viewModel)); }
private CreateMealViewModel CreateTheViewModelForMeal() { var allTypes = this._mealRepository.GetAllMealTypes(); var allIngredients = this._ingredientRepository.ListAllIngredients().Select(i => new SelectListItem { Value = i.Id.ToString(), Text = i.Name }).ToList(); CreateMealViewModel createMealViewModel = new CreateMealViewModel(allIngredients, allTypes); return(createMealViewModel); }
public static Response CreateMeal(CreateMealViewModel model) { using (var unitOfWork = RepoUnitOfWork.New()) { var foodRepo = unitOfWork.Repository <FoodRepository>(); var mealRepo = unitOfWork.Repository <MealRepository>(); var meal = new Recipe { Id = Guid.NewGuid(), Name = model.Name, Description = model.Description, PictureUrl = model.PictureUrl, }; double?caloriValue = 0; var listOfFoodsAssignments = new List <RecipeFoodAssignment>(); if (model.SelectedFoods != null) { foreach (var item in model.SelectedFoods) { var food = foodRepo.Get(item.Id); if (food == null) { unitOfWork.RollbackTransaction(); return(ResponseFactory.ErrorReponse); } caloriValue = (caloriValue + (item.Quantity * food.Calories) / food.Grams) * 100; var foodItems = new RecipeFoodAssignment { FoodId = item.Id, RecipeId = meal.Id, Quantity = item.Quantity }; listOfFoodsAssignments.Add(foodItems); } } meal.Calories = caloriValue ?? caloriValue.Value; meal.RecipeFoodAssignments = listOfFoodsAssignments; var mealCreation = mealRepo.Create(meal); if (mealCreation == null) { unitOfWork.RollbackTransaction(); return(ResponseFactory.ErrorReponse); } unitOfWork.CommitTransaction(); return(ResponseFactory.SuccessResponse); } }
// GET: Meal/Create public IActionResult Create() { CreateMealViewModel model = new CreateMealViewModel(); model.Meal = new Meal(); model.LevelPreperations = new SelectList(_context.LevelPreperations, "LevelPreperationId", "Level"); model.PreperationTimes = new SelectList(_context.PreperationTimes, "PreperationTimeId", "RangeMinutes"); model.Category = new SelectList(_context.Categories, "CategoryId", "Name"); model.SelectedCategories = new List <int>(); return(View(model)); }
public static Response UpdateMeal(CreateMealViewModel model) { using (var mealRepo = RepoUnitOfWork.CreateTrackingRepository <MealRepository>()) using (var foodRepo = RepoUnitOfWork.CreateTrackingRepository <FoodRepository>()) { var currentMeal = mealRepo.Get(model.Id); currentMeal.Name = model.Name; currentMeal.PictureUrl = model.PictureUrl; currentMeal.Description = model.Description; double?caloriValue = 0; var listOfFoodsAssignments = new List <RecipeFoodAssignment>(); if (model.SelectedFoods != null) { foreach (var item in model.SelectedFoods) { var food = foodRepo.Get(item.Id); if (food == null) { return(ResponseFactory.ErrorReponse); } caloriValue = caloriValue + (item.Quantity * food.Calories) / food.Grams; var foodItems = new RecipeFoodAssignment { FoodId = item.Id, RecipeId = currentMeal.Id, Quantity = item.Quantity }; listOfFoodsAssignments.Add(foodItems); } } currentMeal.RecipeFoodAssignments = listOfFoodsAssignments; currentMeal.Calories = caloriValue ?? caloriValue.Value; var updatedMeal = mealRepo.Update(currentMeal); if (updatedMeal == null) { return(ResponseFactory.ErrorReponse); } return(ResponseFactory.SuccessResponse); } }
public ActionResult Create(CreateMealViewModel m) { using (var context = new DinnerManagerContext()) { context.Meals.Add(new Meal { Date = m.Date, Dish = context.Dishes.Single(d => d.Id == m.SelectedDishId) }); context.SaveChanges(); } return RedirectToAction("Index", "Home"); }
public async Task <IActionResult> Create(CreateMealViewModel model, IFormFile ImageData) { try { if (ModelState.IsValid) { using (var memoryStream = new MemoryStream()) { await ImageData.CopyToAsync(memoryStream); if (memoryStream.Length < 2097152) { var data = memoryStream.ToArray(); Meal meal = new Meal { Name = model.Name, Price = model.Price, Description = model.Description, Appetizer = model.Appetizer, MainDish = model.MainDish, Dessert = model.Dessert, ChefId = model.ChefId, Date = model.Date, DayOfTheWeek = model.Date.DayOfWeek.ToString(), Saltless = model.Saltless, Diabetes = model.Diabetes, GlutenAllergy = model.GlutenAllergy, ImageData = Compress(data) }; mealRepository.InsertMeal(meal); return(RedirectToAction("Index")); } else { ModelState.AddModelError("File", "The file is too large."); } } } } catch (DataException) { ModelState.AddModelError("", "Unable to save meal."); } return(View(model)); }
public Response Update(CreateMealViewModel model) { if (model == null) { return(ResponseFactory.ErrorReponse); } var deleteOldPictureResponse = AzureHelper.DeleteFromBlob(model.Id); if (ResponseFactory.IsSuccessful(deleteOldPictureResponse)) { var file = Request.Files["PictureUrl"]; var url = AzureHelper.Upload(file, "PictureUrl", model.Id); model.PictureUrl = url; } return(MealCore.UpdateMeal(model)); }
public JsonResult Save(CreateMealViewModel model) { Response response = null; if (!string.IsNullOrWhiteSpace(model.SelectedFoodsJson)) { model.SelectedFoods = new JavaScriptSerializer().Deserialize <IList <Meal> >(model.SelectedFoodsJson); } if (model.Id == Guid.Empty) { response = Create(model); } else { response = Update(model); } return(Json(response, JsonRequestBehavior.AllowGet)); }
public ActionResult Edit(int id = 0) { Meal meal = mealRepo.GetSingleEntity(x => x.MealId == id); var viewModel = new CreateMealViewModel() { Categories = categoryRepo.GetWithFilterAndOrder(), MealName = meal.MealName, CategoryId = meal.CategoryId, Price = meal.Price, Image = meal.Image, MealId = meal.MealId }; if (meal == null) { return(HttpNotFound()); } return(View(viewModel)); }
public IActionResult CreateMeal(CreateMealViewModel createMealViewModel) { if (!ModelState.IsValid) { return(RedirectToAction("CreateMeal")); } if (createMealViewModel.Type == "Desert" && createMealViewModel.Price < 250) { return(View(this.CreateTheViewModelForMeal())); } Meal meal = new Meal(); meal.Name = createMealViewModel.Name; meal.Price = createMealViewModel.Price; meal.Type = createMealViewModel.Type; meal.Ingredients = createMealViewModel.Ingredients.Select(x => Convert.ToInt32(x)).ToList(); meal.IsVeggie = createMealViewModel.IsVeggie != null ? createMealViewModel.IsVeggie : false; this._mealRepository.CreateMeal(meal); return(RedirectToAction("Index")); }
public Response Create(CreateMealViewModel model) { if (model == null) { return(ResponseFactory.ErrorReponse); } model.Id = Guid.NewGuid(); var file = Request.Files["PictureUrl"]; var url = AzureHelper.Upload(file, "PictureUrl", model.Id); model.PictureUrl = url; var creationResponse = MealCore.CreateMeal(model); if (!ResponseFactory.IsSuccessful(creationResponse)) { var azureResponse = AzureHelper.DeleteFromBlob(model.Id); } return(creationResponse); }
public ActionResult Create(CreateMealViewModel viewModel) { HttpPostedFileBase hpf = Request.Files[0] as HttpPostedFileBase; if (hpf == null || hpf.ContentLength == 0) { ModelState.AddModelError("", "並未選取圖片"); } if (ModelState.IsValid) { Meal meal = new Meal() { CategoryId = viewModel.CategoryId, MealName = viewModel.MealName, Price = viewModel.Price, //TODO: For now only one supplier SupplierId = 1 }; { string savedFileName = Guid.NewGuid().ToString() + "." + (hpf.FileName.Split('.')).Last(); string path = Path.Combine(Server.MapPath("~/Content/ProductImg"), savedFileName); hpf.SaveAs(path); meal.Image = savedFileName; } mealRepo.Insert(meal); mealRepo.SaveChanges(); return(RedirectToAction("Index")); } viewModel.Categories = categoryRepo.GetWithFilterAndOrder(); return(View(viewModel)); }
public async Task <IActionResult> Create(CreateMealViewModel model) { var userId = _userManager.GetUserId(User); EndUser endUser = await _context.EndUsers.FirstOrDefaultAsync(x => x.ApplicationUserId == userId); string uploadedFile = UploadedFile(model.MealImage); if (string.IsNullOrEmpty(uploadedFile)) { ModelState.AddModelError(string.Empty, "Image is not selected"); } if (endUser != null && ModelState.IsValid) { model.Meal.EndUserId = endUser.EndUserId; model.Meal.PictureMeal = uploadedFile; var validator = new MealValidator(_context.Meals); var result = validator.Validate(model.Meal); if (result.IsValid) { if (model.SelectedCategories != null) { List <MealCategory> newCategories = new List <MealCategory>(); foreach (int CategoryId in model.SelectedCategories) { newCategories.Add(new MealCategory { MealId = model.Meal.MealId, CategoryId = CategoryId }); } _context.Add(model.Meal); await _context.SaveChangesAsync(); Meal meal = await _context.Meals .Include(mc => mc.MealCategories) .SingleOrDefaultAsync(meal => meal.MealId == model.Meal.MealId); meal.MealCategories.AddRange(newCategories); _context.Update(meal); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } else { ModelState.AddModelError(string.Empty, "Select at least one category!"); } } else { foreach (var item in result.Errors) { ModelState.AddModelError(string.Empty, item.ErrorMessage); } } } model.LevelPreperations = new SelectList(_context.LevelPreperations, "LevelPreperationId", "Level", model.Meal.LevelPreperationId); model.PreperationTimes = new SelectList(_context.PreperationTimes, "PreperationTimeId", "RangeMinutes", model.Meal.PreperationTimeId); model.Category = new SelectList(_context.Categories, "CategoryId", "Name"); model.SelectedCategories = new List <int>(); return(View(model)); }