Пример #1
0
        public async Task <IActionResult> CreateUserRole(UserViewModel assignUser, List <UserRoleViewModel> UserRole)
        {
            if (ModelState.IsValid)
            {
                List <UserRoleViewModel> roles = new List <UserRoleViewModel>();
                if (UserRole != null)
                {
                    roles = UserRole.Where(x => x.SelectedRole == true).ToList();
                }
                //else
                //{
                //    roles.Add(new UserRoleViewModel { SelectedRole = true, Role = "Enroller" });
                //}

                List <string> selectecRoles = new List <string>();

                foreach (var role in roles)
                {
                    //var isUserinRole = await _userManager.IsInRoleAsync(user, role.Role);
                    //if (isUserinRole && !role.SelectedRole)
                    //{
                    //    await _userManager.RemoveFromRoleAsync(user, role.Role);
                    //}
                    //else
                    //{
                    //    selectecRoles.Add(role.Role);
                    //}
                    selectecRoles.Add(role.Role);
                }


                var result = await _accountManager.AssignUserRoleAsync(assignUser.Id, selectecRoles);

                if (result)
                {
                    //await _userManager.AddToRoleAsync(user, registerViewModel.UserRoles);
                    Alert("Role(s) assigned to user succesfully.", NotificationType.success);
                    return(RedirectToAction("Users"));
                }
                else
                {
                    Alert("Error assigning role(s). Please try again later.", NotificationType.error);
                    return(View("AssignUserRole"));
                }
            }
            Alert("Invalid entries. Please, try again.", NotificationType.info);
            return(View("AssignUserRole"));
        }