I want to show user profile to my _EditUser view and then to edit user profile such as user role .. Name and Email.
But when it comes to user role it's crashing. I get 500 (Internal Server Error) It is crashing here:
model.ApplicationRoleId = RoleManager.Roles.Single(r => r.Name == UserManager.GetRoles(id).Single()).Id;
This is my is my 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; }
}
And this is my 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);
}
In my View page "_EditUser.cshtml" My Dropdownlist of user role looks like this
<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>
/ Thank you in advance