Reputation: 23
I have a ListBox in a View displaying the possible choices. However, the user's role(s) are not shown as selected. In my UserViewModel the Roles collection contains the complete list of roles, and AspNetRoles collection contains only the roles to which the user belongs. I've tried multiple examples/variations but nothing ever shows as selected. I'm stuck.
ViewModel:
public class UserViewModel
{
public string Id { get; set; }
public string Email { get; set; }
public ICollection<AspNetRole> Roles { get; set; }
public virtual ICollection<AspNetRole> AspNetRoles { get; set; }
}
Controller:
public ActionResult Edit(string id)
{
UserViewModel user = new UserViewModel();
AspNetUser aspNetUser = new AspNetUser();
if (!string.IsNullOrEmpty(id))
{
aspNetUser = db.AspNetUsers.Find(id);
user.Id = aspNetUser.Id;
user.Email = aspNetUser.Email;
user.AspNetRoles = aspNetUser.AspNetRoles;
var roles = (from r in db.AspNetRoles
select r).ToList();
user.Roles = roles;
}
return View(user);
}
View:
@Html.ListBox("AspNetRoles",
new MultiSelectList(Model.Roles, "Id", "Name",
Model.AspNetRoles.Select(m => m.Id)))
Upvotes: 2
Views: 4969
Reputation:
You have not posted your model, but it appears that property AspNetRoles
is a collection of a complex object (you cannot bind to a complex object, only a value type - or in the case of ListBox, a collection of value type). You can handle this by changing AspNetRoles
to int[]
(assuming the ID
property of Role
is int
)
@Html.ListBoxFor(m => m.AspNetRoles, new SelectList(Model.Roles, "Id", "Name"))
Note, Its always better to use the strongly typed helpers.
Upvotes: 2