Reputation: 13
I'm learning dotnet6 and this is my first ASP.NET Core 6 MVC project. It's just been 3/4 days I'm learning so it can be an easy solution. I'm trying to get Users to a list but the list seems empty but there are registered users in database.
This is my view:
@model IEnumerable<User>
@{ ViewData["Title"] = "Index";
}
<div class="container p-3">
<div class="row pt-4">
<div class="col-6">
<h2 class="text-primary">User List</h2>
</div>
</div>
<table class="table table-bordered table-striped" style="width:100%">
<thead>
<tr>
<th>
UserName
</th>
<th>
Email
</th>
</tr>
</thead>
<tbody>
@foreach (var obj in Model)
{
<tr>
<td width="50%">
@obj.UserName
</td>
<td width="30%">
@obj.Email
</td>
</tr>
}
This is the model class User
:
public class User : IdentityUser
{
[Required(ErrorMessage = "Email is required")]
[DataType(DataType.EmailAddress)]
public string? Email { get; set;}
[Required(ErrorMessage = "Password is required")]
[DataType(DataType.Password)]
public string Password { get; set; }
public bool RememberMe { get; set; }
[DataType(DataType.DateTime)]
public DateTime LastLoginDate { get; set; } = DateTime.Now;
}
Dbset
of User
in ApplicationDbContext
is
public DbSet<User> Users { get; set; }
Also I've changed AspNetUser
table name to Users
.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUser>(entity =>
{
entity.ToTable("Users");
});
}
UserController code:
public class UserController : Controller
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
private readonly ILogger<UserController> _logger;
private readonly ApplicationDbContext _db;
public UserController(ApplicationDbContext db, UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager, ILogger<UserController> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
_db = db;
}
// GET: /<controller>/
public IActionResult Index()
{
IEnumerable<User> objUserList = _db.Users;
return View(objUserList);
}
}
I've done login and register methods, also with IdentityUser
and they both work.
I have the same codes for another Categories
model and it shows categories without any problem but can't do the same with Users
.
Categories page:
User List page:
Upvotes: 0
Views: 363
Reputation: 819
Hi this is my working code, I hope you register everything correctly in the Program.cs
private UserManager<IdentityUser> userManager;
private RoleManager<IdentityRole> roleManager;
private readonly WorkshopProContext _cs;
public UsersAdmin(UserManager<ApplicationUser> usrMgr, RoleManager<IdentityRole> roleManager, WorkshopProContext cs)
{
userManager = usrMgr;
this.roleManager = roleManager;
_cs = cs;
}
public IActionResult Index()
{
return View(userManager.Users.ToList());
}
Upvotes: 1