public ActionResult Edit(int?userPK) { if (userPK != null) { IRolesRepository rolesRepository = new RolesRepository(db); IUsersRepository usersRepository = new UsersRepository(db); User user = usersRepository.GetUserByUserID((int)userPK); UserAccountView userAccountView = new UserAccountView(); userAccountView.ConvertFrom(user, userAccountView); IUsersInRolesRepository usersInRolesRepository = new UsersInRolesRepository(db); var rolesSelectedValues = usersInRolesRepository.GetRolesByUserPK((int)userPK).Select(uir => uir.RoleFK); userAccountView.Roles = new MultiSelectList(rolesRepository.GetActiveRoles().ToList(), "RolePK", "Name", rolesSelectedValues); return(View(userAccountView)); } else { return(RedirectToAction("Index", "User")); } }
public ActionResult Add(UserAccountView userAccountView, FormCollection form) { IUsersRepository usersRepository = new UsersRepository(db); if (userAccountView.Username != null) { if (usersRepository.GetUserByUsername(userAccountView.Username) != null) { ModelState.AddModelError("Username", "Korisničko ime već postoji."); } } if (userAccountView.Email != null) { if (usersRepository.GetUserByEmail(userAccountView.Email) != null) { ModelState.AddModelError("Email", "E-mail već postoji."); } } if (ModelState.IsValid) { string sessionToken = Audit.GenerateNewSessionToken(); User user = new User(); userAccountView.RegistrationDate = DateTime.Now; PBKDF2 pbkdf2 = new PBKDF2(userAccountView.Password); var passwordBytes = pbkdf2.ComputePBKDF2(); userAccountView.Password = Convert.ToBase64String(passwordBytes); userAccountView.Salt = Convert.ToBase64String(pbkdf2.SaltBytes); string[] rolesSelectedValues = new string[100]; if (form["RolePK"] != null) { rolesSelectedValues = ((string)form["RolePK"]).Split(','); } userAccountView.ConvertTo(userAccountView, user); usersRepository.Add(user); usersRepository.SaveChanges(sessionToken); // Delete old roles IUsersInRolesRepository usersInRolesRepository = new UsersInRolesRepository(db); usersInRolesRepository.Delete(uir => uir.UserFK == user.UserPK); // Add New Roles foreach (string role in rolesSelectedValues) { UserInRole tmpUserInRole = new UserInRole(); tmpUserInRole.UserFK = user.UserPK; tmpUserInRole.RoleFK = Convert.ToInt32(role); usersInRolesRepository.Add(tmpUserInRole); } usersInRolesRepository.SaveChanges(sessionToken); TempData["message"] = LayoutHelper.GetMessage("INSERT", user.UserPK); return(RedirectToAction("Index", "User")); } else { string[] rolesSelectedValues = new string[100]; if (form["RolePK"] != null) { rolesSelectedValues = ((string)form["RolePK"]).Split(','); } IRolesRepository rolesRepository = new RolesRepository(db); userAccountView.Roles = new MultiSelectList(rolesRepository.GetActiveRoles(), "RolePK", "Name", rolesSelectedValues); return(View(userAccountView)); } }