List of users and roles using the membership provider

I am trying to create a view to show a list of users and their role using the built-in membership provider.

My model and controller collect users and roles, but Im having problems 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> 
+3
source share
2 answers

As Andrei said, you need to do a view inheritance from AdminViewModel , not IEnumerable<AdminViewModel> . Once this is fixed, you will need to Model.Users over Model.Users instead of Model in foreach . Model.Users will contain 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> <% }%> 
+1
source

What is the problem? Make sure that in the debugger the lists placed in the model are filled (not empty).

By the way:

 foreach (var item in Model) 

it looks like you mentioned

 foreach (var item in Model.Users) 
0
source

All Articles