Update User Role ASP.NET Identity

0

Hello everyone, I'm finding it difficult to update the user role when updating my data, my roles are being filled through a ViewBag in my get from my controller and I'm retrieving the new ID in the post from my controller through the request. form follows the code of 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.

    
asked by anonymous 14.12.2018 / 21:53

1 answer

1

Then issue solved 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.

    
18.12.2018 / 01:37