// GET: Admin/Cakes/Edit/5 public async Task <IActionResult> Edit(int?id) { if (id == null) { return(NotFound()); } var cake = await context.Cakes.FindAsync(id); if (cake == null) { return(NotFound()); } var viewModel = new EditCakeViewModel { Id = cake.Id, Name = cake.Name, Description = cake.Description, ImageUrl = cake.ImageUrl, Price = cake.Price }; // Retrieve categories for dropdown box var categories = context.Categories.ToList() .Select(c => new SelectListItem { Value = c.Id.ToString(), Text = c.Name.ToString() }).ToList(); ViewBag.Categories = categories; return(View(viewModel)); }
public async Task <IActionResult> Edit(int id, EditCakeViewModel viewModel) { if (id != viewModel.Id) { return(NotFound()); } if (ModelState.IsValid) { // Retrieve associated category (in case of unselection, category id will be set to default value "1") string categoryIdString = Request.Form["Categories"]; bool categoryIdIsValid = int.TryParse(categoryIdString, out int categoryIdParsed); int categoryId = categoryIdIsValid ? categoryIdParsed : 0; var associatedCategory = await context.Categories.FindAsync(categoryId); // Retrieve located cake and its categories var locatedCake = await context.Cakes.Include(c => c.Categories).FirstOrDefaultAsync(c => c.Id == viewModel.Id); var locatedCakeCategories = locatedCake.Categories.ToList(); locatedCake.Name = viewModel.Name; locatedCake.Description = viewModel.Description; locatedCake.ImageUrl = viewModel.ImageUrl; locatedCake.Price = viewModel.Price; // Context multiple tracking problem (context cannot track same ids simultaneously) //var cake = new Cake( // viewModel.Id, // viewModel.Name, // viewModel.Description, // viewModel.ImageUrl, // viewModel.Price // ); if (associatedCategory != null && !locatedCakeCategories.Contains(associatedCategory)) { locatedCake.Categories.Add(associatedCategory); } try { context.Update(locatedCake); await context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CakeExists(locatedCake.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(viewModel)); }