ASP.NET MVC 中如何在 .cshtml 界面引入数据实体表
在 ASP.NET MVC 中,可以通过以下步骤引入数据实体表:
- 在 Model 文件夹中创建一个数据实体类,例如 Student.cs:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
- 在 Controller 中创建一个 Action,例如 Index:
public ActionResult Index()
{
List<Student> students = new List<Student>();
students.Add(new Student { Id = 1, Name = 'Tom', Age = 18 });
students.Add(new Student { Id = 2, Name = 'Jerry', Age = 20 });
return View(students);
}
- 在 Views 文件夹中创建一个 .cshtml 文件,例如 Index.cshtml,引入数据实体类:
@model List<Student>
@foreach (var student in Model)
{
<p>@student.Name</p>
}
在这个例子中,我们通过在 Controller 的 Index Action 中创建了一个包含两个 Student 对象的 List,并将它作为参数传递给了 Index.cshtml 视图。在视图中,我们通过 @model 指令将数据实体类 Student 引入,并使用 @foreach 循环遍历 List 中的每个 Student 对象,输出每个对象的 Name 属性。
原文地址: https://www.cveoy.top/t/topic/mHWk 著作权归作者所有。请勿转载和采集!