tags:

views:

29

answers:

2

I’m trying to produce a view to show a list of users and their role using the built in membership provider.

My model and controller are picking up the users and roles but I’m having trouble displaying them in my view.

Model

public class AdminViewModel
    {
        public MembershipUserCollection Users { get; set; }
        public string[] Roles { get; set; }
    }

Controller

public ActionResult Admin()
{
      AdminViewModel viewModel = new AdminViewModel
      {
            Users = MembershipService.GetAllUsers(),
        Roles = RoleService.GetRoles()
      };

      return View(viewModel);
}

View

Inherits="System.Web.Mvc.ViewPage<IEnumerable<Account.Models.AdminViewModel>>"

<table>

<tr>
    <td>UserName</td>
    <td>Email</td>
    <td>IsOnline</td>
    <td>CreationDate</td>
    <td>LastLoginDate</td>
    <td>LastActivityDate</td>
</tr>

<% foreach (var item in Model) { %>

<tr>
    <td><%=item.UserName %></td>
    <td><%=item.Email %></td>
    <td><%=item.IsOnline %></td>
    <td><%=item.CreationDate %></td>
    <td><%=item.LastLoginDate %></td>
    <td><%=item.LastActivityDate %></td>
    <td><%=item.ROLE %></td>
</tr>

<% }%>

</table>
A: 

What kind of trouble it is? Please, make sure under debugger that lists you put into model are populated (non-empty).

By the way:

foreach (var item in Model)

looks like you mentioned

foreach (var item in Model.Users) 
Andrew Florko
When I use foreach (var item in Model.Users) I'm not picking up the Users model.
Jemes
When I debug the site the model in my controller has values for Users and Roles.
Jemes
Please, remove IEnumerable<...> from you model type definition. You pass only one instance of AdminViewModel Inherits="System.Web.Mvc.ViewPage<IEnumerable<Account.Models.AdminViewModel>>
Andrew Florko
A: 

Like Andrew said, you need to make your View inherit from AdminViewModel, not IEnumerable<AdminViewModel>. Once that is corrected you'll need to iterate over Model.Users, instead of Model in your foreach. Model.Users will contain the MembershipUser objects with the Username property.

<% foreach (var item in Model.Users) { %>

<tr>
    <td><%=item.UserName %></td>
    <td><%=item.Email %></td>
    <td><%=item.IsOnline %></td>
    <td><%=item.CreationDate %></td>
    <td><%=item.LastLoginDate %></td>
    <td><%=item.LastActivityDate %></td>
    <td><%=item.ROLE %></td>
</tr>

<% }%>
Nathan Taylor
I've removed the IEnumerable and added Model.Users but I'm now getting the error... 'object' does not contain a definition for 'UserName' and no extension method 'UserName' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?
Jemes
Please post your updated code.
Nathan Taylor