Search code examples
asp.netasp.net-membershipasp.net-roles

ASP.Net Membership: List Roles in Listbox


I'm trying to put together a custom user update page so you can update a user's email, password and role all on one page. I'm stuck on the roles. I have listed the roles ok, but I want to select the role allocated to the user in a listbox.

In this case each user will only have one role.

I've tried playing around with Roles.GetRolesForUser("userName"); without much luck.

Here's the listbox code:

<asp:ListBox ID="myRoles" runat="server"
     SelectionMode="Single" >
</asp:ListBox>

And here's the databinding for the Listbox:

rolesArray = Roles.GetAllRoles();
myRoles.DataSource = rolesArray;
myRoles.DataBind();

What's the easiest to get this to work?


Solution

  • protected void Page_Load(object sender, EventArgs e)
        {
            var allRoles = new[] {"Admin", "Client", "Super Admin", "Other"};
    
            //Returns string array
            var rolesByUser = Roles.GetRolesForUser(HttpContext.User.Identity.Name);
    
            myRoles.DataSource = allRoles;
            myRoles.DataBind();
    
            foreach (ListItem role in myRoles.Items)
            {
                foreach (var userRole in rolesByUser)
                {
                    if (role.Text == userRole)
                        role.Selected = true;
                }
            }
        }
    

    Then in your html:

    <asp:ListBox ID="myRoles" SelectionMode="Multiple" runat="server"></asp:ListBox>
    

    Single Role/Single Selection Only

    Change loop to :

    foreach (ListItem role in myRoles.Items)
            {
                if (role.Text == rolesByUser.FirstOrDefault())
                    role.Selected = true;
            }
    

    Alternatives

    Here's a shorter version of that loop using LINQ to Objects:

        foreach (ListItem role in myRoles.Items)
                {
                    foreach (var userRole in rolesByUser
                                        .Where(userRole => role.Text == userRole))
                    {
                        role.Selected = true;
                    }
                }
    

    And finally a pure LINQ mode that is in my opinion a bit too hard to read:

    foreach (ListItem role in from ListItem role in myRoles.Items 
                    from userRole in rolesByUser.Where(userRole => role.Text == userRole) 
                    select role)
            {
                role.Selected = true;
            }