Update Role of the ASP.NET Identity user

Asked

Viewed 105 times

0

hello guys I am finding it difficult to update the user role when updating my data, my roles are being filled by a Viewbag in my get from my controller and I am retrieving the new ID from my controller post via the request.form follow the code from my post.

    [AllowAnonymous]
    [HttpPost]
    public ActionResult UserEdit(ApplicationUser appuser)
    {

        var context = new Models.ApplicationDbContext();
        var user = context.Users.Where(u => u.Id == appuser.Id).FirstOrDefault();
        user.LockoutEnabled = appuser.LockoutEnabled;

        //Recupera o ID do novo item
        var newRole = Request.Form["RoleId"].ToString();

        //Aqui eu deveria a atualização da role


        context.SaveChanges();
        return RedirectToAction("UserList");
    }

thank you all.

1 answer

1


Then question resolved as follows

    [HttpPost]
    [AccessDeniedAuthorizeAttribute(Roles = "Administrador")]
    public ActionResult UserEdit(ApplicationUser appuser)
    {
        var context = new Models.ApplicationDbContext();
        var user = context.Users.Where(u => u.Id == appuser.Id).FirstOrDefault();
        user.LockoutEnabled = appuser.LockoutEnabled;

        //Recupera o ID da nova Role onde esse e um Dropdownlist na minha view
        int newRole = Convert.ToInt32(Request.Form["RoleId"].ToString());
        var role = context.Roles.Where(u => u.Id == newRole.ToString()).FirstOrDefault();
        var oldRoleId = user.Roles.SingleOrDefault().RoleId;
        var oldRoleName = context.Roles.SingleOrDefault(r => r.Id == oldRoleId).Name;

        //Aqui eu atualizo a minha role
        UserManager.RemoveFromRole(user.Id, oldRoleName);
        UserManager.AddToRole(user.Id, role.Name);

        context.SaveChanges();
        return RedirectToAction("UserList");
    }

Thank you all.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.