简体   繁体   中英

MVC 5 Identity. Roles for User

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>

Here's how I did it.

Create an extension method on role manager, replace ApplicationRole with whatever class name you're using for your roles.

public static class RoleManagerExtensions
{
    public static List<CheckBoxItem> GetRolesSelectList(
        this RoleManager<ApplicationRole> roleManager,
        IList<string> selectedValues)
    {
        List<CheckBoxItem> roles = 
            roleManager.Roles.ToList().Select(r => new CheckBoxItem
        {
            Selected = selectedValues.Contains(r.Name),
            Id = r.Name,
            Name = r.Name
        }).ToList();
        return roles;
    }
}

Here's the CheckBoxItem POCO:

public class CheckBoxItem
{
    public bool Selected { get; set; }
    public string Id { get; set; }
    public string Name { get; set; }
}

In your controller get the roles list and pass in the selected roles:

var selectedRoles = await _userManager.GetRolesAsync(user);
List<CheckBoxItem> roles = _roleManager.GetRolesSelectList(selectedRoles);

In your View, you can create your checkboxes like so:

 @for (int i = 0; i < Model.Roles.Count; i++)
 {
     <input type="checkbox" asp-for="@Model.Roles[i].Selected" />
     <label asp-for="@Model.Roles[i].Selected">@Model.Roles[i].Name</label>
     <input type="hidden" asp-for="@Model.Roles[i].Id" />
     <input type="hidden" asp-for="@Model.Roles[i].Name" />
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM