Exemplo n.º 1
0
        public ActionResult EditUser(string id)
        {
            var context           = new AppSecurityContext();
            var rolRepository     = new RoleRepository(context);
            var userRolRepository = new UserRoleRepository(context);

            var user  = context.Users.Find(id);
            var model = new EditAppUserViewModel();

            model.Email = user.Email;
            model.Id    = user.Id;

            var roles = rolRepository.GetAll();

            var assignedRoles = userRolRepository.GetAssignedUserRoles(id);

            if (assignedRoles.Count() > 0)
            {
                model.SelectedRoles = assignedRoles.Select(x => x.RoleId).ToArray();
            }
            else
            {
                model.SelectedRoles = new string[0];
            }
            model.AvailableRoles = mapper.Map <ICollection <AppRoleViewModel> >(roles);
            return(View(model));
        }
Exemplo n.º 2
0
        public ActionResult EditUser(string id, EditAppUserViewModel model)
        {
            var context           = new AppSecurityContext();
            var rolRepository     = new RoleRepository(context);
            var userRolRepository = new UserRoleRepository(context);

            if (ModelState.IsValid)
            {
                //Se asignan los roles
                var user          = mapper.Map <AppUser>(model);
                var assignedRoles = userRolRepository.GetAssignedUserRoles(id);
                var selectedRoles = new List <AppRole>();
                if (model.SelectedRoles != null)
                {
                    foreach (var rolId in model.SelectedRoles)
                    {
                        selectedRoles.Add(new AppRole {
                            Id = rolId
                        });
                    }
                }
                userRolRepository.UpdateUserWithRoles(user, selectedRoles);
                try
                {
                    context.SaveChanges();
                }
                catch
                {
                    return(View(model));
                }
                return(RedirectToAction("Users"));
            }

            var roles = rolRepository.GetAll();

            model.AvailableRoles = mapper.Map <ICollection <AppRoleViewModel> >(roles);
            return(View(model));
        }