public async Task <IActionResult> Edit(int id, [Bind("Id,Name,Calories,DateEntered,UserId")] Foodinfo foodinfo) { if (id != foodinfo.Id) { return(NotFound()); } if (ModelState.IsValid) { bool emptyInput = false; ViewBag.NameError = "Nothing"; ViewBag.CalorieError = "Nothing"; if (foodinfo.Name == null || foodinfo.Name.Trim().Length == 0) { emptyInput = true; ViewBag.NameError = "Please enter an food."; } if (foodinfo.Calories == null || foodinfo.Calories <= 0) { emptyInput = true; ViewBag.CalorieError = "Please add calories."; } if (emptyInput) { ViewData["UserId"] = new SelectList(_context.AspNetUsers, "Id", "Id", foodinfo.UserId); return(View(foodinfo)); } try { _context.Update(foodinfo); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!FoodinfoExists(foodinfo.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["UserId"] = new SelectList(_context.AspNetUsers, "Id", "Id", foodinfo.UserId); return(View(foodinfo)); }
public async Task <IActionResult> Create([Bind("Id,Name,Calories,DateEntered,UserId")] Foodinfo foodinfo) { //makes sure its not null if (foodinfo.Name != null) { //get calories... //change spaces to %20 if (foodinfo.Name.Replace(" ", "%20").Length != 0) { foodinfo.Name = foodinfo.Name.Replace(" ", "%20"); //call api string url = "https://api.nal.usda.gov/fdc/v1/foods/search?api_key=4yzPQJ6HCWvpCWm6KGaZr1QdIl3UkLhzdXs7os8o&query=" + foodinfo.Name; //change spaces back :P foodinfo.Name = foodinfo.Name.Replace("%20", " "); HttpClient client = new HttpClient(); string response = await client.GetStringAsync(url); //use json parser var myJObject = JObject.Parse(response); //check if there was at least one hit int hits = (int)myJObject["totalHits"]; //if theres at least one valid hit then proceed if (hits > 0) { //stores all nutrient info for the first food IList <JToken> results = myJObject["foods"].ElementAt <JToken>(0)["foodNutrients"].ToList(); IList <FoodNutrients> foodNutrients = new List <FoodNutrients>(); //loop through all Jtokens and map them to a class foreach (JToken result in results) { FoodNutrients foodNutrient = result.ToObject <FoodNutrients>(); foodNutrients.Add(foodNutrient); } //loop through list of nutrients to get energy foreach (FoodNutrients nutrient in foodNutrients) { if (nutrient.nutrientName.Equals("Energy")) { //finally set calories to the energy value... YAY! foodinfo.Calories = (int)nutrient.value; } } //set date foodinfo.DateEntered = DateTime.Now; //set user id string userID = User.FindFirstValue(ClaimTypes.NameIdentifier); // I tottally just stole grey's way, cause I don't know a better way.... foodinfo.UserId = userID; if (ModelState.IsValid) { _context.Add(foodinfo); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["UserId"] = new SelectList(_context.AspNetUsers, "Id", "Id", foodinfo.UserId); } } } return(View(foodinfo)); }