簡體   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