WHAT I AM TRYING TO ACHIEVE
If a user is a member of 3 roles, i want to generate 3 DropDownLists of all roles and each user role to be selected. I dont want to use ViewBag.
PROBLEM
Currently, i can generate 3 DropDownLists which contain all roles, but the 3 roles that the user is a member of are not selected. If the user is a member of Admin, PowerUser, and Manager roles, only the last role, Manager, is selected in all 3 DropDownLists.
QUESTION
How do i generate the required DropDownLists with the correctly selected roles?
VIEWMODEL
public class UserViewModel
{
public IEnumerable<SelectListItem> RolesList { get; set; }
public string RolesListId { get; set; }
}
CONTROLLER
// Get list of roles that user is a member of
var userRoles = UserManager.GetRoles(user.Id);
var model = new UserViewModel()
{
RolesList = RoleManager.Roles.ToList().Select(r => new SelectListItem
{
Selected = userRoles.Contains(r.Name),
Text = r.Name,
Value = r.Name
}).OrderBy(r => r.Text),
};
VIEW
@for (int i = 0; i < Model.RolesList.Where(x => x.Selected == true).Count(); i++)
{
@Html.DropDownListFor(model => model.RolesListId, Model.RolesList, "Select Role ...")
}