我正在尝试显示另一个对象中的一个对象的值。几天来我一直在重写它,并用谷歌搜索它以试图找出我哪里出错了。我从一个复杂得多的项目开始,但现在我写了一个非常简单的学校项目,用作示例并尝试不同的东西。我已经根据 Internet 上的示例以至少 30 种不同的方式重写了配置,但到目前为止没有任何效果。非常感谢任何帮助我摆脱困境的帮助!
类:
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; }
}
配置:
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
}
);
}
}
查看:
@model IEnumerable<school.Models.Course>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.courseName)
</th>
<th>
@Html.DisplayNameFor(model => model.teacher.name)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.courseName)
</td>
<td>
@Html.DisplayFor(modelItem => item.teacher.name)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
如何让教师的姓名显示在类(class) View 中?
如果我在 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());
}
所以问题一定出在我播种数据的方式上,对吧?
最佳答案
这些行:
<td>
@Html.DisplayFor(modelItem => item.courseName)
</td>
<td>
@Html.DisplayFor(modelItem => item.teacher.name)
</td>
在 lambda 中:
DisplayFor(modelItem => item.teacher.name)
看起来你拿错了东西。
虽然,根据您创建迭代的方式,您为什么不使用:
@item.teacher.name
代替:
@Html.DisplayFor(modelItem => item.teacher.name)
关于c# - 我是在正确地播种数据还是做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40428341/