public async Task <IActionResult> Edit(int id, [Bind("TrailId,TrailName,Location")] Trail trail)
        {
            if (id != trail.TrailId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(trail);
                    await _context.SaveChangesAsync();

                    TempData["UserMessage"] = $"Trail successfully edited!";
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TrailExists(trail.TrailId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(trail));
        }
示例#2
0
        public async Task <IActionResult> Edit(int id, [Bind("UserId,LastName,FirstName,Age,Bio,SelectedHikes")] User hiker)
        {
            if (id != hiker.UserId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    List <Hike> existingHikes = _context.Hike.Where(h => h.UserId == hiker.UserId).ToList();

                    foreach (int TrailId in hiker.SelectedHikes)
                    {
                        if (existingHikes.Where(h => h.TrailId == TrailId).Count() == 0)
                        {
                            _context.Hike.Add(new Hike()
                            {
                                TrailId = TrailId,
                                UserId  = hiker.UserId
                            });
                        }
                    }



                    foreach (Hike hike in existingHikes)
                    {
                        if (hiker.SelectedHikes.Where(TrailId => TrailId == hike.TrailId).Count() == 0)
                        {
                            _context.Hike.Remove(hike);
                        }
                    }

                    _context.Update(hiker);
                    await _context.SaveChangesAsync();

                    TempData["UserMessage"] = $"User successfully edited!";
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!HikerExists(hiker.UserId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(hiker));
        }