I need to display set of checkboxes to being able to manage user roles. I can give to my view all of existing roles:
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new MlmDbContext()));
ViewBag.allRoles = roleManager.Roles.ToList();
And I can get roles for user into the view :
@{
foreach (var role in Model.Roles)
{
But what should I do to show ALL roles with binding to Model.Roles and than save changes?
you put the id of the roles as value on the form and then receive a table of int of selected roles il controller
In one of my projectt this is part of codes that should interest you:
Controller that provide data to the view:
public async Task<ActionResult> Create()
{
// Get the list of Roles
ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");
return View();
}
View that shows roles:
<div class="form-group">
<label class="col-md-2 control-label">
@Resources.Global.SelectRole
</label>
<div class="col-md-10">
@foreach (var item in (SelectList)ViewBag.RoleId)
{
<input type="checkbox" name="SelectedRoles" value="@item.Value" class="checkbox-inline" />
@Html.Label(item.Value, new { @class = "control-label" })
}
</div>
</div>
Controller that receive roles selected :
[HttpPost]
public async Task<ActionResult> Create(RegisterViewModel userViewModel, params string[] selectedRoles)
{
if (ModelState.IsValid)
{...}
}
EDIT:
OK so this is what I think you need:
In the Controller:
RolesList = RoleManager.Roles.ToList().Select(x => new SelectListItem()
{
Selected = userRoles.Contains(x.Name),
Text = x.Name,
Value = x.Name
}),
In the view:
<div class="form-group">
@Html.Label("Roles", new { @class = "control-label col-md-2" })
<span class=" col-md-10">
@foreach (var item in Model.RolesList)
{
<input type="checkbox" name="SelectedRole" value="@item.Value" checked="@item.Selected" class="checkbox-inline" />
@Html.Label(item.Value, new { @class = "control-label" })
}
</span>
</div>