public ActionResult Update(int id) { User user = userService.GetByIdWithDetails(id); RoleSelectionViewModel roleModel = new RoleSelectionViewModel(); List <Role> roles = roleService.GetAll(); ViewBag.Departments = new SelectList(departmentService.GetAll(), "Id", "Name"); UserWithRoleSelectViewModel model = new UserWithRoleSelectViewModel { Department = user.Department, Id = user.Id, Name = user.Name, Surname = user.Surname, Username = user.Username }; model.RoleSelections = new List <RoleSelectionViewModel>(); foreach (var item in roles) { model.RoleSelections.Add(new RoleSelectionViewModel { Id = item.Id, Name = item.Name, isSelected = user.UserRoles?.FirstOrDefault(x => x.RoleId == item.Id) != null }); } return(View(model)); }
public ActionResult Update(UserWithRoleSelectViewModel model) { if (ModelState.IsValid) { if (IsUserNameValid(model.Id, model.Username)) { User user = new User { Id = model.Id, Name = model.Name, Surname = model.Surname, Username = model.Username, DepartmentId = model.Department?.Id > 0 ? (int?)model.Department.Id : null }; model.RoleSelections = model.RoleSelections.FindAll(x => x.isSelected); user.UserRoles = new List <UserRole>(); if (model.RoleSelections?.Count > 0) { foreach (var item in model.RoleSelections) { user.UserRoles.Add(new UserRole { RoleId = item.Id }); } } userService.Update(user); return(RedirectToAction("Index")); } else { ModelState.AddModelError("", "Bu isimde bir kullanıcı adı zaten var."); } } ViewBag.Departments = new SelectList(departmentService.GetAll(), "Id", "Name"); return(View(model)); }