簡體   English   中英

Asp.Net Mvc編輯具有用戶角色的用戶配置文件

[英]Asp.Net Mvc Edit User profile with user Role

當我想獲取當前用戶角色名稱,要編輯用戶配置文件時,為什么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;

但是字符串existRole對我不起作用。

我將不勝感激。

我確實喜歡@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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM