ASP.NET Core MVC实现从数据库加载数据到HTML表格的方法
实现ASP.NET Core MVC从数据库动态加载数据到HTML表格
1. 定义数据模型
先创建与表格字段匹配的实体类,示例如下:
public class User { public string Email { get; set; } public string Name { get; set; } public string Level { get; set; } public string Location { get; set; } }
2. 控制器获取数据库数据
方式一:使用EF Core(推荐)
假设你已经配置好DbContext,控制器通过依赖注入获取上下文并查询数据:
using Microsoft.AspNetCore.Mvc; using YourProjectNamespace.Data; // 替换为你的DbContext命名空间 public class UserController : Controller { private readonly AppDbContext _dbContext; public UserController(AppDbContext dbContext) { _dbContext = dbContext; } public IActionResult Index() { // 从数据库查询数据,可按需添加过滤、排序逻辑 var userList = _dbContext.Users.ToList(); return View(userList); } }
方式二:使用ADO.NET
如果直接用原生数据库操作,示例如下:
using Microsoft.AspNetCore.Mvc; using System.Data.SqlClient; using System.Collections.Generic; using YourProjectNamespace.Models; // 替换为你的模型命名空间 public class UserController : Controller { private readonly string _connString; public UserController(IConfiguration config) { _connString = config.GetConnectionString("DefaultConnection"); } public IActionResult Index() { List<User> userList = new List<User>(); using (SqlConnection conn = new SqlConnection(_connString)) { string query = "SELECT Email, Name, Level, Location FROM Users"; conn.Open(); using (SqlCommand cmd = new SqlCommand(query, conn)) { using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { userList.Add(new User { Email = reader["Email"].ToString(), Name = reader["Name"].ToString(), Level = reader["Level"].ToString(), Location = reader["Location"].ToString() }); } } } } return View(userList); } }
3. 修改Razor视图绑定数据
在你的CSHTML文件顶部添加模型声明,然后在<tbody>中循环渲染数据:
@model List<YourProjectNamespace.Models.User> <!-- 替换为你的模型命名空间 --> <style> table { margin: 0 auto; margin-top: 20px; width: 100%; position: relative; overflow: auto; overflow-y: overlay; } th, thead { position: sticky; top: 0; border: 1px solid #dddddd; background-color: #1f2d54; text-align: center; color: white; table-layout: fixed; word-break: break-word; height: 45px; } </style> <table style='padding: 8px;'> <thead> <tr> <th index=0>Email<div class="filter"></div></th> <th index=1>Name<div class="filter"></div></th> <th index=2>Level<div class="filter"></div></th> <th index=3>Location<div class="filter"></div></th> </tr> </thead> <tbody> @foreach (var user in Model) { <tr> <td>@user.Email</td> <td>@user.Name</td> <td>@user.Level</td> <td>@user.Location</td> </tr> } </tbody> </table>
补充说明
- 确保
appsettings.json中配置了正确的数据库连接字符串 - 若需分页、筛选功能,可在控制器中接收查询参数,修改数据查询逻辑
内容的提问来源于stack exchange,提问作者KitKat
相关产品推荐
相关产品推荐

