papapi
papapi

Reputation: 61

ASP.NET Identity - How to get a dropdown list of all users

Have have added Fullname to my identity user claim here:

public string Fullname { get { return this.Firstname + " " + this.Lastname; } }

now I'm trying to populate a dropdownlist (Full names) of all the users

In my controller i have :

      var users = Roles.GetUsersInRole("*");
        SelectList list = new SelectList(users);
        ViewBag.Users = list;

and in my view I have:

   @Html.DropDownList("Users", ViewBag.Users as SelectList);

But I get an error highlighting the "Users" in my view.

System.InvalidOperationException: 'There is no ViewData item of type 'IEnumerable' that has the key 'Users'.'

Is there a better way to archive what i'm trying to do? please help

Upvotes: 1

Views: 1878

Answers (3)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

Roles.GetUsersInRole() returns string[] array, you can use overloaded Enumerable.Select() method to create SelectList from it:

var users = Roles.GetUsersInRole("RoleName");
var list = users.Select((x, index) => new SelectListItem { Text = x, Value = index.ToString() });
ViewBag.Users = list;

An alternative to get SelectList from user with specified role should be like this:

var users = Roles.GetUsersInRole("RoleName").Select(Membership.GetUser).ToList();
var list = users.Select(x => new SelectListItem { Text = x.UserName, Value = Membership.GetUser(x.UserName).ProviderUserKey.ToString() }).ToList();
ViewBag.Users = list;

Note: For ASP.NET Identity 2, you may use Users and Roles with data context to create SelectList as in example below:

using (var context = new ApplicationDbContext())
{
    var users = from u in context.Users
        where u.Roles.Any(r => r.Role.Name == "RoleName")
        select u;

    // ViewBag.Users = new SelectList(users, "Id", "UserName");
    ViewBag.Users = users.Select(x => new SelectListItem { Text = x.UserName, Value = x.Id }).ToList();
}

Upvotes: 0

Richard Hubley
Richard Hubley

Reputation: 2320

Try creating a List like below. Choose a proper value for Text and Value.

var users = Roles.GetUsersInRole("*");
    var list = users.Select(x => new SelectListItem(){ Text = x.FullName, Value = x.FullName);
    ViewBag.Users = list;

Upvotes: 1

Antoine V
Antoine V

Reputation: 7204

Try using

@Html.DropDownList("Users", "Users list");

Upvotes: 1

Related Questions