繁体   English   中英

ASP.NET 核心在页面上显示数据库中的所有行

[英]ASP.NET Core display all rows in database on page

我正在尝试使用 ASP.NET Core MVC 在网站上显示数据库中的每一行,但我找不到任何有关如何执行此操作的资源。这是我尝试做的,但我卡住了:

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();
            
        }

我的数据库的结构是这样的:ID、用户名、密码、密码哈希,但我只想显示用户名开头。

如果您有任何来源或想法,将非常感激! 预先感谢!

最好的问候马克斯

如果你真的想使用原始的 ADO.NET,那么好吧,我给你举个例子。

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);
}

您不需要向数据库发出两个请求——这非常浪费。

您只想显示用户名,因此只请求它就足够了。

我建议你使用最大的 ORM for .NET,Entity Framework。

创建这个

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options): base(options)
    {
    }

    public DbSet<UserModel> Users { get; set; }
}

添加到 Startup.cs 中的 ConfigureServices 方法

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(
        options => options.UseSqlServer({"your_connection_string"}));
}

在您的 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);
    }
}

那么,在你看来

@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>

参考https://docs.microsoft.com/pt-br/ef/core/dbcontext-configuration/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM