public ActionResult AddBooks(int id, AddBookToShelfViewModel model) { if (!ModelState.IsValid) { return(View(model)); } if (model.SelectedShelfId != id) { ModelState.AddModelError("", "ID Mismatch, please try again."); return(View(model)); } var service = CreateBookshelfService(); var books = new ApplicationDbContext().Books.ToList(); var bookList = new SelectList(books.Select(item => new SelectListItem { Text = item.Title, Value = item.BookId.ToString() }).ToList(), "Value", "Text"); if (service.AddBookToShelf(model)) { TempData["SaveResult"] = "Your book was added to the shelf."; return(RedirectToAction("Details", new { id = model.SelectedShelfId })); } ModelState.AddModelError("", "Your book could not be added."); return(View(model)); }
//Books to Shelves //Working with ShelfRecordKeeper entities to connect books to shelves public bool AddBookToShelf(AddBookToShelfViewModel model) { using (var ctx = new ApplicationDbContext()) { var shelfToAddBookTo = ctx .Bookshelves .Single(s => s.ShelfId == model.SelectedShelfId && s.UserId == _userId); var bookToAddToShelf = ctx .Books .Single(b => b.BookId == model.SelectedBookId); var shelfRecordToCreate = new ShelfRecordKeeper { ShelfId = shelfToAddBookTo.ShelfId, BookId = bookToAddToShelf.BookId }; ctx.ShelfRecords.Add(shelfRecordToCreate); return(ctx.SaveChanges() == 1); } }
//BOOKS // GET: BooksToAdd public ActionResult AddBooks(int id) { var svc = CreateBookshelfService(); var model = svc.GetBookshelfById(id); var books = new ApplicationDbContext().Books.ToList(); var bookList = new SelectList(books.Select(item => new SelectListItem { Text = item.Title, Value = item.BookId.ToString() }).ToList(), "Value", "Text"); var viewModel = new AddBookToShelfViewModel() { SelectedShelfId = model.ShelfId, BookListItems = bookList, }; return(View(viewModel)); }