2017-10-14 125 views
0

爲什麼我的Action在Asp.Net Mvc代碼崩潰時想獲取當前用戶角色名稱,當我想編輯用戶配置文件? 此代碼崩潰Asp.Net Mvc編輯用戶配置文件與用戶角色

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並沒有爲我工作..

我會greateful任何幫助..

+0

您不應該使用Result來調用異步方法。等待你的方法,如'var r = await UserManager.GetRolesAsync(user.Id); var existingRole = u.First();'當你確定你的集合總是隻有一個項目時,也使用Single方法,否則會拋出'InvalidOperationException'異常。 – Shyju

+0

@Shyju謝謝你的迴應,但你是什麼意思var r = await UserManager.GetRolesAsync(user.Id);?在哪裏放置這個結果?你的意思是model.ApplicationRoleId =等待UserManager.GetRolesAsync(user.Id);?然後var existingRole = u.First()?你來了哪裏?你必須在某處申報......我的意思是我應該初始化我的模型.ApplicationRoleId? 。再次感謝你。 –

+0

@Shyju,請你幫忙..? –

回答

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 .... 

    } 

謝謝喲u @Shyju