My goal is simple. I want to list all registered users in my ASP.NET MVC5 for administrational purposes. Here's my AccountController code:
[Authorize(Roles = "Admin")]
public ActionResult AdminUserManagement()
{
var context = new IdentityDbContext();
var allUsers = context.Users.ToList();
var viewModels = new List<ManagerUserViewModel>();
foreach (var user in allUsers)
{
viewModels.Add(new ManagerUserViewModel { UserID = user.Id, UserName = user.UserName, Role = user.Roles.First().Role.ToString() });
}
return View(viewModels);
}
But fore some reason the allUsers list, is empty. When I run the application, The View works just fine, but picks up no Users at all.
The View:
@model IEnumerable<GUI.Models.ManagerUserViewModel>
@{
ViewBag.Title = "User Management";
}
<h2>User Management</h2>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.UserName)
</th>
<th>
@Html.DisplayNameFor(model => model.Role)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Role)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
The IdentityDB:
using ClassLibrary.Entities;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace DAL.DataContexts
{
public class IdentityDb : IdentityDbContext<ApplicationUser>
{
public IdentityDb()
: base("WhitelabelDb")
{
}
}
}
What's wrong with my code, and why?
Well, looking at your code I can't see a bigger problem, but you aren't disposing your database context as you should. Try the following code and see if it helps:
[Authorize(Roles = "Admin")]
public ActionResult AdminUserManagement()
{
IEnumerable<ManagerUserViewModel>() viewModels;
using(var context = new IdentityDbContext()){
viewModels =
context.Users
.Include("Roles")
.Select(u =>
new ManagerUserViewModel {
UserID = u.Id,
UserName = u.UserName,
Role = u.Roles.First().Role.ToString()
}
).ToList();
}
return View(viewModels);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With