public async Task <IActionResult> ManageRolesForUser(string id)
    {
        if (string.IsNullOrEmpty(id))
        {
            return(RedirectToAction(nameof(Index)));
        }

        var user = await _userMgr.FindByNameAsync(id);

        var userRoles = await _userMgr.GetRolesAsync(user);

        var model = new ManageRolesForUserModel {
            Username = id
        };

        model.AllRoles.AddRange(await _repo.GetAllRoleNamesAsync());
        model.GrantedRoles.AddRange(userRoles);

        return(View(model));
    }
    public async Task <IActionResult> ManageRolesForUser(IFormCollection collection)
    {
        if (collection == null)
        {
            throw new ArgumentNullException(nameof(collection));
        }

        string username = collection["Username"];
        var    model    = new ManageRolesForUserModel
        {
            Username = username
        };

        model.AllRoles.AddRange(await _repo.GetAllRoleNamesAsync());

        var user = await _userMgr.FindByNameAsync(username);

        var currRoles = await _userMgr.GetRolesAsync(user);

        var newRoleList = new List <string>();

        if (!string.IsNullOrEmpty(collection["role"]))
        {
            newRoleList.AddRange(collection["role"]);
        }

        var toRemove = currRoles.Where(cm => !newRoleList.Any(nm => string.Equals(cm, nm, StringComparison.OrdinalIgnoreCase)));
        var toAdd    = newRoleList.Where(nm => !currRoles.Any(cm => string.Equals(cm, nm, StringComparison.OrdinalIgnoreCase)));
        var errs     = new List <IdentityError>();

        _log.LogInformation("new roles: {Roles}", string.Join(", ", newRoleList));

        foreach (var role in toRemove)
        {
            var result = await _userMgr.RemoveFromRoleAsync(user, role);

            if (!result.Succeeded)
            {
                errs.AddRange(result.Errors);
            }
        }

        foreach (var role in toAdd)
        {
            var result = await _userMgr.AddToRoleAsync(user, role);

            if (!result.Succeeded)
            {
                errs.AddRange(result.Errors);
            }
        }

        if (errs.Any())
        {
            model.Result = IdentityResult.Failed(errs.ToArray());
        }
        else
        {
            model.Result = IdentityResult.Success;
        }

        // after the changes, get the new membership info (we are now
        user = await _userMgr.FindByNameAsync(username);

        currRoles = await _userMgr.GetRolesAsync(user);

        model.GrantedRoles.AddRange(currRoles);

        return(View(model));
    }