Reputation: 450
I am trying to display every row from a database on a website with ASP.NET Core MVC, but I cannot find any source on how to do it.. This is what Ive tried to do but I got stuck:
public IActionResult Index()
{
connection.Open();
command.Connection = connection;
command.CommandText = "SELECT COUNT(*) FROM Users;";
var rows = Convert.ToInt32(command.ExecuteReader());
command.Dispose();
List<UserModel> users = new List<UserModel>();
for(int i = 0; i <= rows; i++)
{
users.Add(new UserModel(ID, "", ""));
}
command.CommandText = "SELECT * FROM Users";
dataReader = command.ExecuteReader();
return View();
}
My Database is structured like this: Id, Username, Password, PasswordHash, but I only want to display Username to begin with.
If you have any sources or ideas it would be very appriciated! Thanks beforehand!
Best Regards Max
Upvotes: 2
Views: 1518
Reputation: 14231
If you really want to use raw ADO.NET, then okay, I'll show you an example.
public IActionResult Index()
{
using var connection = new SqlConnection(_connectionString);
connection.Open();
using var command = new SqlCommand();
command.Connection = connection;
command.CommandText = "SELECT Username FROM Users;";
using var reader = command.ExecuteReader();
List<UserModel> users = new List<UserModel>();
while (reader.Read())
{
string name = reader.GetString(0);
users.Add(new UserModel { Name = name });
}
return View(users);
}
You don't need to make two requests to the database - this is very wasteful.
You want to show only the Username, so it is enough to request only it.
Upvotes: 3
Reputation: 416
I recommend you to use the biggest ORM for .NET, Entity Framework.
Create this
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options): base(options)
{
}
public DbSet<UserModel> Users { get; set; }
}
Add to the ConfigureServices method in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(
options => options.UseSqlServer({"your_connection_string"}));
}
On your controller
public class YourController : Controller
{
private ApplicationDbContext ApplicationDbContext { get; }
public YourController(ApplicationDbContext applicationDbContext)
{
ApplicationDbContext = applicationDbContext;
}
public async Task<IActionResult> Index()
{
var users = await ApplicationDbContext.Users.ToListAsync();
return View(users);
}
}
Then, on your view
@model List<YourNamespace.UserModel>
<table>
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
@foreach (var user in Model)
{
<tr>
<th>@user.Name</th>
</tr>
}
</tbody>
</table>
References https://learn.microsoft.com/pt-br/ef/core/dbcontext-configuration/
Upvotes: 2