在ASP.NET Core MVC中,从数据库中获取数据并将其显示在视图中的最简单的方法是使用控制器中的Action方法,将数据存储在模型中并将模型传递给视图。以下是一个简单的示例:
public class StudentModel { public int Id { get; set; } public string Name { get; set; } }
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions
public DbSet Students { get; set; }
}
public class StudentController : Controller { private readonly SchoolContext _context;
public StudentController(SchoolContext context)
{
_context = context;
}
public IActionResult Index()
{
List students = _context.Students.ToList();
return View(students);
}
}
@model IEnumerable
@{ ViewData["Title"] = "Student List"; }
Id | Name |
---|---|
@student.Id | @student.Name |
在Startup类中的ConfigureServices方法中注册数据库上下文服务:
services.AddDbContext
请注意,在以上代码示例中,假定已经存在数据库配置文件appsettings.json,并且也已经安装了适当的NuGet包。