Ejemplo n.º 1
0
        // GET: Periods/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Period period = db.Period.Find(id);
            if (period == null)
            {
                return HttpNotFound();
            }
            ViewBag.ProjectId = new SelectList(db.Project, "Id", "Name", period.ProjectId);
            ViewBag.Users = identityDb.Users.ToList();

            var model = new PeriodViewModel();
            model.Period = period;
            //model.UserPeriods = db.UserPeriod.Where(up => up.PeriodId == period.Id).ToList();

            var allUsers = identityDb.Users.ToList();
            model.AllUsers = allUsers.Select(o => new SelectListItem
            {
                Text = o.UserName,
                Value = o.Id.ToString()
            });

            model.SelectedUsers = db.UserPeriod.Where(up => up.PeriodId == period.Id).Select(up => up.UserId).ToList();

            return View(model);
        }
Ejemplo n.º 2
0
        public ActionResult Edit(PeriodViewModel model)
        {
            if (ModelState.IsValid)
            {
                //var periodToUpdate = db.Period.First(i => i.Id == model.Period.Id);

                var currentUserperiods = db.UserPeriod.Where(up => up.PeriodId == model.Period.Id);
                var currentUserIds = currentUserperiods.Select(up => up.UserId).ToList();

                var selectedUsers = new HashSet<int>();
                if (model.SelectedUsers != null)
                    selectedUsers = new HashSet<int>(model.SelectedUsers);

                foreach (var user in identityDb.Users)
                {
                    if (currentUserIds.Contains(user.Id) && !selectedUsers.Contains(user.Id))
                    {
                        db.UserPeriod.Remove(currentUserperiods.First(up => up.UserId == user.Id));
                    }
                    else if (!currentUserIds.Contains(user.Id) && selectedUsers.Contains(user.Id))
                    {
                        db.UserPeriod.Add(new UserPeriod { UserId = user.Id, PeriodId = model.Period.Id });
                    }
                }

                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.ProjectId = new SelectList(db.Project, "Id", "Name", model.Period.ProjectId);
            return View(model);
        }