// GET: ShoppingList public ActionResult AddToShoppingList(string item, int listId) { var currentuserid = User.Identity.GetUserId(); var user = _dataRepository.GetCurrentUser(currentuserid); var errormsg = ""; var items = _dataRepository.GetAllItems(); if (!String.IsNullOrEmpty(item) && _dataRepository.FindItemByNameToLowerCase(item) != null) { var theitem = _dataRepository.FindItemByNameToLowerCase(item); var thelist = _dataRepository.FindUserShoppingList(user ,listId); //var thelist = user.ShoppingLists.Where(sl => sl.Id == listId).First(); if (thelist.ItemsAndLists.FirstOrDefault(x => x.Item.Name == theitem.Name) != null) { errormsg += item + " was already added to the " + thelist.Name + " list."; return Json(new { found = false, error = errormsg }, JsonRequestBehavior.AllowGet); } ItemAndShoppingList iands = new ItemAndShoppingList { Item = theitem, ItemId = theitem.Id, ShoppingList = thelist, ShoppingListId = thelist.Id, QuantityBought = 1 }; ItemViewModel i = new ItemViewModel { Id = theitem.Id, Name = theitem.Name, Price = theitem.Price, InStock = theitem.InStock, StockAmount = theitem.StockAmount, Aisle = theitem.Aisle, Section = theitem.Section, Allergens = theitem.Allergens }; _dataRepository.AddItemToItemAndListTable(theitem, iands); _dataRepository.AddShoppingListToItemAndListTable(thelist, iands); //thelist.ItemsAndLists.Add(iands); //theitem.ItemAndLists.Add(iands); //_db.SaveChanges(); return Json(new { found = true, itemfound = theitem.Name, sectionofitem = theitem.Section, list = thelist.Name }, JsonRequestBehavior.AllowGet); //return Json(new { found = true, itemfound = theitem.Name, list = thelist.Name }, JsonRequestBehavior.AllowGet); } errormsg += item + " was not found in our database"; return Json(new { found = false, error = errormsg }, JsonRequestBehavior.AllowGet); }