我想将两个模型传递给View。 我有两个型号
public class Department
{
public int DepartmentID { get; set; }
public string DepartmentName { get; set; }
public string Image { get; set; }
public List<Teacher> Teachers { get; set; }
}
和第二
public class Teacher
{
public int TeacherID { get; set; }
public string TeacherName { get; set; }
public string TeacherLname { get; set; }
public int DepartmentID { get; set; }
public string Image { get; set; }
public Department Department { get; set; }
}
我制作了一个ViewModel
public class ViewModel
{
public List<Teacher> Teachers { get; set; }
public List<Department> Departments { get; set; }
}
我的控制器
public ActionResult Index()
{
ViewModel model = new ViewModel();
// retreive from database
model.Teachers = new List<Teacher>() { new Teacher() };
model.Departments = new List<Department>() { new Department() };
return View(model);
}
和我在视图中的a
@model Tuple<IEnumerable<_167School.Models.Teacher>,IEnumerable<_167School.Models.Department>>
@foreach (var student in Model.Item2)
{
<tr>
<td>@student.DepartmentName</td>
</tr>
}
@foreach (var teacher in Model.Item1)
{
<tr>
<td>@teacher.TeacherName</td>
<td>@teacher.TeacherLname</td>
<td>@teacher.DepartmentID</td>
</tr>
}
并且网站继续运行并告诉我
The model item passed into the dictionary is of type '_167School.ViewModels.ViewModel', but this dictionary requires a model item of type 'System.Tuple`2[System.Collections.Generic.IEnumerable`1[_167School.Models.Teacher],System.Collections.Generic.IEnumerable`1[_167School.Models.Department]]'.
我想在一个视图中显示两个模型数据。我试过这种方式。
请帮助 谢谢
答案 0 :(得分:3)
您将ViewModel
类型传递给视图,但您的视图将模型声明为Tuple<T1, T2>
。将视图更改为
@model YourAssembly.ViewModel
然后使用
遍历集合@foreach (var teacher in Model.Teachers)
{
<tr>
<td>@teacher.TeacherName</td>
<td>@teacher.TeacherLname</td>
<td>@teacher.DepartmentID</td>
</tr>
}