gpt4 book ai didi

c# - 如何显示对象内对象字段的值?

转载 作者:行者123 更新时间:2023-11-28 01:04:43 25 4
gpt4 key购买 nike

我真的不知道用什么词来问我需要的问题,这意味着我没有真正从谷歌获得任何东西,所以我只是想创建一个简单的例子。如果您能回答我的问题或只是指出我需要搜索的方向,那就太好了。

假设我有这些类(class):

 public class Teacher
{
public int teacherID { get; set; }
public string name { get; set; }
}

public class Course
{
[Key]
public int ID { get; set; }
public string courseName { get; set; }
public int? teacherID { get; set; }
public Teacher teacher { get; set; }
}

public class schoolDBContext : DbContext
{
public DbSet<Course> Courses { get; set; }
public DbSet<Teacher> Teachers { get; set; }
}

如何在显示类(class)时以 HTML 格式显示教师姓名。例如,当我有下面的 View 时,老师的名字是空白的。我需要更改什么才能显示该类(class)的教师姓名?

<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.teacher.Name)
</th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.teacher.Name)
</td>
</tr>
}

这是我重写了大约 30 次的配置:

 protected override void Seed(school.Models.schoolDBContext context)
{
context.Courses.AddOrUpdate(i => i.ID,
new Course
{
courseName = "Math",
teacher = new Teacher { teacherID = 1, name = "Ms. Brooks" },
teacherID = 1
},
new Course
{
courseName = "Science",
teacher = new Teacher { teacherID = 2, name = "Ms. James" },
teacherID = 2
},
new Course
{
courseName = "History",
teacher = new Teacher { teacherID = 3, name = "Ms. Davidson" },
teacherID = 3
}
);
}

页面看起来像这样。 enter image description here

但是如果我为 Controller 这样做:

public ActionResult Index()
{
var _coursesList = new List<Course>();
_coursesList.Add(new Course { ID = 1, courseName = "English", teacherID = 1, teacher = new Teacher { teacherID = 1, name = "Mrs. Thomas" } });
_coursesList.Add(new Course { ID = 2, courseName = "History", teacherID = 2, teacher = new Teacher { teacherID = 2, name = "Ms. Jones" } });
_coursesList.Add(new Course { ID = 3, courseName = "Math", teacherID = 2, teacher = new Teacher { teacherID = 2, name = "Ms. Fisher" } });

return View(_coursesList);

// return View(db.Courses.ToList());
}

我明白了:

enter image description here

最佳答案

确保你已经填充了模型对象

例如:

 public ActionResult Index()
{
var _courselst = new List<Course>();
_courselst.Add(new Course { CourseID = 1, Name = "IT", Teacher = new Teacher { Name = "Scot", TeacherID = 1 } });
_courselst.Add(new Course { CourseID = 2, Name = "ACC", Teacher = new Teacher { Name = "Manj", TeacherID = 2 } });
_courselst.Add(new Course { CourseID = 3, Name = "MATHS", Teacher = new Teacher { Name = "Demion", TeacherID = 3 } });

return View(_courselst);
}

关于c# - 如何显示对象内对象字段的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40412841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com