Search code examples
asp.netasp.net-mvcasp.net-mvc-5asp.net-identity

ASP.NET MVC 5 - Default Identity user CRUD


I am new to ASP.NET MVC.

I have created an application using default identity individual user accounts. I am trying to implement an admin panel and I would like to view all the users, their roles and edit / delete them (CRUD Operation).

I came across the following:

userManager.Users.ToList();

public ActionResult Index()
{
    return userManager.Users.ToList();
}

I have tried researching regarding the same. Unfortunately, I am unable to implement it.


Solution

  • In ASP.NET Identity 2.0 which you are probably using, what you need is exposed on the UserManager and RoleManager.

    userManager.Users.ToList();
    roleManager.Roles.ToList();
    

    You can use those two managers to create roles and assign roles to users. For example to get users in specific roles you can do something like that:

    var users = roleManager.FindByName(roleName).Users.Select(x => x.UserId);
    

    To delete user you can do something like that:

    [ValidateAntiForgeryToken]
    public async Task<ActionResult> DeleteConfirmed(string id)
    {
        if (ModelState.IsValid)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
    
            var user = await _userManager.FindByIdAsync(id);
            var logins = user.Logins;
            var rolesForUser = await _userManager.GetRolesAsync(id);
    
            using (var transaction = context.Database.BeginTransaction())
            {
                foreach (var login in logins.ToList())
                {
                    await _userManager.RemoveLoginAsync(login.UserId, new UserLoginInfo(login.LoginProvider, login.ProviderKey));
                }
    
                if (rolesForUser.Count() > 0)
                {
                    foreach (var item in rolesForUser.ToList())
                    {
                        // item should be the name of the role
                        var result = await _userManager.RemoveFromRoleAsync(user.Id, item);
                    }
                }
    
                await _userManager.DeleteAsync(user);
                transaction.commit();
            }
    
            return RedirectToAction("Index");
        }
        else
        {
            return View();
        }
    }
    

    And if you would like to update an user then:

    var user = UserManager.FindById(User.Identity.GetUserId())
    
    user.Email = AppUserViewModel.Email;
    user.FName = AppUserViewModel.FName;
    user.LName = AppUserViewModel.LName;
    user.DOB = AppUserViewModel.DOB;
    user.Gender = AppUserViewModel.Gender;
    
    var result = await UserManager.UpdateAsync(user);