添加而不是更新用户角色

时间:2017-09-28 19:29:07

标签: c# asp.net-mvc-5

我正在尝试从下拉菜单更新用户角色。当我选择用户名(电子邮件地址)和我想要分配它们并点击提交的角色(例如SuperUser,Admin,User)时,我会按照它应该提交所有内容。我发现,对于我为同一个用户选择更新的角色,我为该角色创建了一个数据条目,并为用户增加了一次。这使得输入的最后一条记录始终是userRole。

我无法弄清楚一旦找到用户,删除当前的RoleId并添加新的.I / p>

如果您想要查看,模型或其他任何其他代码,请告诉我并发布它。

底部的图像,例如数据库中发生的事情。

控制器

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> RegisterRole(RegisterViewModel model, ApplicationUser user)
    {

        var userId = db.AspNetUsers.Where(i => i.UserName == user.UserName).Select(s => s.Id);
        string updateId = "";
        foreach (var i in userId)
        {
            updateId = i.ToString();
        }
        //Assign Role to user here
        await this.UserManager.AddToRoleAsync(updateId, model.Name);

        return RedirectToAction("Index", "Employee");
    }

Repeat records

1 个答案:

答案 0 :(得分:2)

有两种方法可以派上用场:1)GetRolesAsync 获取所有用户角色,2)在添加新角色之前使用RemoveFromRoleAsync删除它们

var roles = await this.UserManager.GetRolesAsync(userId);
await this.UserManager.RemoveFromRolesAsync(userId, roles.ToArray());

//then add new role 
await this.UserManager.AddToRoleAsync(userId, roleName);

编辑:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> RegisterRole(RegisterViewModel model, ApplicationUser user)
{

    //in case user is being passed in without Id (unlikely), you could use user manager to get the full user object 
    //user = await this.UserManager.FindByNameAsync(user.UserName);

    //get all user's roles, and remove them
    var roles = await this.UserManager.GetRolesAsync(user.Id);
    await this.UserManager.RemoveFromRolesAsync(user.Id, roles.ToArray());

    //Assign Role to user here
    await this.UserManager.AddToRoleAsync(user.Id, model.Name);

    return RedirectToAction("Index", "Employee");
}
相关问题