Asp.Net Mvc使用用户角色编辑用户配置文件

时间:2017-10-14 21:06:44

标签: asp.net-mvc user-roles

当我想要获取当前用户角色名称时,为什么我的Asp.Net Mvc代码中的Action会崩溃? 此代码崩溃

model.ApplicationRoleId = roleManager.Roles.Single(r => r.Name == userManager.GetRolesAsync(user).Result.Single()).Id;

我得到的错误信息是:500(内部服务器错误)

这是我的EditUserview

public class EditUserViewModel
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public List<SelectListItem> ApplicationRoles { get; set; }

    public string ApplicationRoleId { get; set; }

    public List<SelectListItem> DepartmentNames { get; set; }

    public int DeptId { get; set; }   // I have DeptId too in my AspNetUser table
}

我的Edituser行动

    [HttpGet]
public async Task<IActionResult> EditUser(string id)
{
    EditUserViewModel model = new EditUserViewModel();
    model.ApplicationRoles = roleManager.Roles.Select(r => new SelectListItem
    {
        Text = r.Name,
        Value = r.Id
    }).ToList();

    model.DepartmentNames = context.Departments.Select(s => new SelectListItem
    {

        Text = s.DeptName,
        Value = s.DeptId.ToString()
    }).ToList();

    if (!String.IsNullOrEmpty(id))
    {
        ApplicationUser user = await userManager.FindByIdAsync(id);
        if (user != null)
        {
            model.Name = user.Name;
            model.Email = user.Email;
            model.DeptId = user.DepartmentId;
           //model.ApplicationRoleId crashing
            model.ApplicationRoleId = roleManager.Roles.Single(r => r.Name == userManager.GetRolesAsync(user).Result.Single()).Id; // Here crashing .. I don't know why.. Server 500 error

            ViewBag.RoleId = new SelectList(RoleManager.Roles, "Id", "Name", model.ApplicationRoleId);
            ViewBag.DeptId = new SelectList(db.Departments, "Deptd", "DeptName", model.DeptId);


        }
    }
    return PartialView("_EditUser", model);
}

我试过这样但是即便崩溃......

string existingRole = UserManager.GetRolesAsync(user.Id).Result.Single();// This crashing

然后放在这里:

string existingRoleId = RoleManager.Roles.Single(r => r.Name == existingRole).Id;

但字符串existingRole对我不起作用..

我会对任何帮助都很有帮助。

1 个答案:

答案 0 :(得分:0)

我确实喜欢这样的@Shyju写道

 var role = await UserManager.GetRolesAsync(user.Id);
                        var existingRole = role.First();
     if (existingRole != null)
      {
     string existingRoleId = RoleManager.Roles.Single(r => r.Name == existingRole).Id;
    model.ApplicationRoleId = existingRoleId;
    .....  and so on ....

   }

谢谢@Shyju