Ejemplo n.º 1
0
        public ActionResult UserEdit(UserViewModel model)
        {
            if (ModelState.IsValid)
            {
                //userManager = new ApplicationUserManager(new ApplicationUserStore(identityDb));
                userManager = new ApplicationUserManager(new ApplicationUserStore(identityDb));

                var currentUser = identityDb.Users.Find(model.UserId);
                var currentRoles = currentUser.Roles;
                var currentRoleIds = currentRoles.Select(r => r.RoleId);

                var selectedRoles = new HashSet<int>();
                if (model.SelectedRoles != null)
                    selectedRoles = new HashSet<int>(model.SelectedRoles);

                foreach (var role in identityDb.Roles.ToList())
                {
                    if (currentRoleIds.Contains(role.Id) && !selectedRoles.Contains(role.Id))
                    {
                        userManager.RemoveFromRole(currentUser.Id, role.Name);
                    }
                    else if (!currentRoleIds.Contains(role.Id) && selectedRoles.Contains(role.Id))
                    {
                        userManager.AddToRole(currentUser.Id, role.Name);
                    }
                }
                return RedirectToAction("Users");
            }
            return View(model);
        }
Ejemplo n.º 2
0
        public ActionResult UserEdit(int? id)
        {
            var user = identityDb.Users.Find(id);
            var model = new UserViewModel { UserId = user.Id, UserName = user.UserName, Role = "" };

            var allRoles = identityDb.Roles.ToList();
            model.AllRoles = allRoles.Select(o => new SelectListItem
            {
                Text = o.Name,
                Value = o.Id.ToString()
            });
            model.SelectedRoles = user.Roles.Select(r => r.RoleId).ToList();
            return View(model);
        }