public ActionResult Create(FormCollection frmc) { var mealName = frmc["name"]; var recipe = frmc["recipe"]; var ir = new IngredientRepository(); var ingredients = ir.GetAll(UserController.currentUser.Id); var mealIngredients = new List <Ingredient>(); var quanitites = new List <int>(); var ingredientsQuantites = new List <MealIngredientQuantity>(); for (int i = 1; i < frmc.Count - 1; i++) { if (i % 2 != 0) { mealIngredients.Add(ingredients.Where(ing => ing.Id.ToString().Equals(frmc[i])).FirstOrDefault()); } else { int quantity; quantity = (Int32.TryParse(frmc[i], out quantity)) ? quantity : 0; quanitites.Add(quantity); } } var mr = new MealRepository(); for (int i = 0; i < mealIngredients.Count; i++) { ingredientsQuantites.Add(new MealIngredientQuantity() { CreatedByUser = UserController.currentUser.Id, IngredientId = mealIngredients.ElementAt(i).Id, IngredientName = mealIngredients.ElementAt(i).Name, IngredientCarbohydrates = mealIngredients.ElementAt(i).Carbohydrates, IngredientFat = mealIngredients.ElementAt(i).Fat, IngredientProteins = mealIngredients.ElementAt(i).Proteins, IngredientCalories = mealIngredients.ElementAt(i).Calories, Quantity = quanitites.ElementAt(i) }); } var meal = mr.Create(new Meal() { Name = mealName, CreatedByUser = UserController.currentUser.Id, MealIngredientQuantites = ingredientsQuantites, Recipe = recipe }); return(RedirectToAction("Meals")); }
public ActionResult <Meal> Post(Meal meal) { if (!ModelState.IsValid) { logger.Info("Meal ModelState is not valid."); return(BadRequest()); } try { return(Ok(mealRepository.Create(meal))); } catch (Exception ex) { logger.Error(ex); return(BadRequest(ex)); } }