2

I have a situation where I need to populate a drop-down list using the below code. I use this code in one situation by setting (and I get a list of all users as expected):

var users = Membership.GetAllUsers();

but if I use

var users = Roles.GetUsersInRole("MyRole");

my drop-down does not populate with any users (I am certain I have users in the listed role).

Do I need to change my controller to use a different type aside from "MemberShipUser" ?

Do I need to approach the situation in an entirely different fashion since I am using roles instead of a list of users?

Here is my code -

Controller:

var users = Roles.GetUsersInRole("MyRole");
var model = new CreateStudentViewModel
{
    Users = users.OfType<MembershipUser>().Select(x => new SelectListItem
    {
        Value = x.UserName,
        Text = x.UserName,
    })
};

ViewModel:

public class MyViewModel
{
    [Display(Name = "selected user")]
    public string SelectedUser { get; set; }
    public IEnumerable<SelectListItem> Users { get; set; }
}

View:

    <div class="editor-label">
        @Html.LabelFor(model => model.SelectedUser)
    </div>

    <div class="editor-field">
        @Html.LabelFor(x => x.SelectedUser)
        @Html.DropDownListFor(x => x.SelectedUser, Model.Users)
    </div>
Ecnalyr
  • 5,792
  • 5
  • 43
  • 89
  • I see I am approaching the situation incorrectly - this post http://stackoverflow.com/a/9157588/1026898 mentions "If you want to map the returned username to a MembershipUser you can use Membership.GetUser(string username) method on each of the returned values." - but I'm not exactly sure how I would get a list from that - I know how to get the one user, but not a list. – Ecnalyr Mar 09 '12 at 14:52

2 Answers2

1

Roles.GetUsersInRole("MyRole") returns string[] not list of MembershipUsers.

users.OfType<MembershipUser>() gives you empty enumeration.

Check the method return type before you call it, or RTM ;-)

Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126
0

Try:

@Html.DropDownList("SelectedUsers", new SelectList((IEnumerable<SelectListItem>)ViewData["Users"], "Id", "Name"))

Where in your controller:

ViewData["Users"] = Roles.GetUsersInRole("MyRole");
Kadir.K
  • 366
  • 4
  • 17
  • Will not work because Roles.GetUsersInRole returns a string, not a list of members. "Unable to cast object of type 'System.String[]' to type 'System.Collections.Generic.IEnumerable`1[System.Web.Mvc.SelectListItem]'." – Ecnalyr Mar 09 '12 at 14:51