我想将用户个人资料显示到我的_EditUser视图,然后编辑用户个人资料,例如用户角色..姓名和电子邮件。
但是当涉及到用户角色时,它正在崩溃。我得到500(内部服务器错误) 它崩溃了:
model.ApplicationRoleId = RoleManager.Roles.Single(r => r.Name == UserManager.GetRoles(id).Single()).Id;
这是我的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; }
}
这是我的EditUser Action
[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();
if (!String.IsNullOrEmpty(id))
{
ApplicationUser user = await userManager.FindByIdAsync(id);
if (user != null)
{
model.Name = user.Name;
model.Email = user.Email;
model.ApplicationRoleId = RoleManager.Roles.Single(r => r.Name == UserManager.GetRoles(id).Single()).Id; // Here crashing .. I don't know why.. Server 500 error
ViewBag.RoleId = new SelectList(RoleManager.Roles, "Id", "Name", model.ApplicationRoleId);
}
}
return PartialView("_EditUser", model);
}
在我的视图页面“_EditUser.cshtml”我的用户角色下拉列表如下所示
<div class="form-group">
@Html.Label("Role", htmlAttributes: new { @class = "control-label col-md-6" })
<div class="col-md-12" >
@Html.DropDownList("RoleId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.ApplicationRoles, "", new { @class = "text-danger" })
</div>
</div>
/提前谢谢
答案 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