public async Task <IActionResult> Create(MealsIndexViewModel model) { if (ModelState.IsValid) { try { Meal meal = new Meal { EventId = model.EventId, BreakfastPrice = model.BreakfastPrice, DinnerPrice = model.DinnerPrice, LunchPrice = model.LunchPrice, VenueName = model.VenueName, AppUserId = (string)ViewBag.UserId }; await _context.Meals.AddAsync(meal); await _context.SaveAsync(); } catch (Exception exp) { ModelState.AddModelError("err", exp.Message); } } return(RedirectToAction(nameof(Index))); }
public async Task <IActionResult> Edit(int?id, MealsIndexViewModel model) { if (id == null || id != model.Id) { return(NotFound()); } Event selectedEvent = _context.Events.FindOnly(x => x.Id == model.EventId).SingleOrDefault(); if (selectedEvent == null) { return(NotFound()); } if (ModelState.IsValid) { Meal currentMeal = _context.Meals.Find(x => x.Id == model.Id).SingleOrDefault(); if (currentMeal != null) { using (var transaction = _context.Database.BeginTransaction()) { try { //delete first _context.Meals.Remove(currentMeal); await _context.SaveAsync(); currentMeal = new Meal(); //then add new one currentMeal.VenueName = model.VenueName; currentMeal.BreakfastPrice = model.BreakfastPrice; currentMeal.DinnerPrice = model.DinnerPrice; currentMeal.LunchPrice = model.LunchPrice; currentMeal.EventId = model.EventId; currentMeal.AppUserId = ViewBag.UserId; await _context.Meals.AddAsync(currentMeal); await _context.SaveAsync(); //commit transaction transaction.Commit(); } catch (Exception exp) { ModelState.AddModelError("err", exp.Message); transaction.Rollback(); } } } return(RedirectToAction(nameof(Index))); } else { return(View(model)); } }