我想通过在一个视图中使用两个模型来显示两个不同数据库表的数据。 我的EnrolmentWithCourses方法 HomeController.cs
public ActionResult EnrolmentWithCourses()
{
List<object> myModelCollection = new List<object>();
myModelCollection.Add(db.Enrollments.ToList());
myModelCollection.Add(db.Courses.ToList());
return View(myModelCollection);
}
我的观点 EnrolmentWithCourses.cshtml 是:
@model IEnumerable<object>
@{
List<ContosoUniversity.Models.Course> CourseList = Model.ToList()[0] as List<ContosoUniversity.Models.Course>;
List<ContosoUniversity.Models.Enrollment> EnrollmentList = Model.ToList()[1] as List<ContosoUniversity.Models.Enrollment>;
}
<h2>Course List</h2>
@foreach (var item in CourseList)
{
<li> @item.CourseID </li>
<li> @item.Title</li>
}
<h2>Course List</h2>
@foreach (var item in EnrollmentList)
{
<li> @item.EnrollmentID</li>
<li> @item.CourseID</li>
<
}
答案 0 :(得分:3)
您的问题是Model.ToList()[0]
是List<ContosoUniversity.Models.Enrollment>
而不是List<ContosoUniversity.Models.Course>
,因为在您的控制器中,您在db.Enrollments.ToList()
之前添加了db.Courses.ToList()
:
List<object> myModelCollection = new List<object>();
myModelCollection.Add(db.Enrollments.ToList());
myModelCollection.Add(db.Courses.ToList());
return View(myModelCollection);
如果您更改订单,它将起作用:
List<object> myModelCollection = new List<object>();
myModelCollection.Add(db.Courses.ToList());
myModelCollection.Add(db.Enrollments.ToList());
return View(myModelCollection);
<强> BUT 强> 我强烈建议创建一个强类型模型来避免这类问题:
public class YourModel
{
public IList<ContosoUniversity.Models.Enrollment> Enrollments {get;set}
public IList<ContosoUniversity.Models.Course> Courses {get;set}
}
控制器操作将如下:
public ActionResult EnrolmentWithCourses()
{
var model = new YourModel{
Enrollments = db.Enrollments.ToList(),
Courses = db.Courses.ToList()
};
return View(model);
}
查看
@model YourModel
<h2>Course List</h2>
@foreach (var item in Courses)
{
<li> @item.CourseID </li>
<li> @item.Title</li>
}
<h2>Course List</h2>
@foreach (var item in Enrollments)
{
<li> @item.EnrollmentID</li>
<li> @item.CourseID</li>
<
}
答案 1 :(得分:1)
您应该创建一个如下所示的复合模型:
public class EnrolmentWithCoursesModel
{
List<ContosoUniversity.Models.Course> CourseList {get; set; }
List<ContosoUniversity.Models.Enrollment> EnrollmentList {get; set; }
}
现在更改您的操作以返回视图的复合模型:
public ActionResult EnrolmentWithCourses()
{
EnrolmentWithCoursesModel myModelCollection = new EnrolmentWithCoursesModel() { CourseList = db.Courses.ToList(), EnrollmentList = db.Enrollments.ToList() };
return View(myModelCollection);
}
现在,您的视图应更改为模型以生成EnrolmentWithCoursesModel
@model EnrolmentWithCoursesModel
<h2>Course List</h2>
@foreach (var item in Model.CourseList)
{
<li> @item.CourseID </li>
<li> @item.Title</li>
}
<h2>Course List</h2>
@foreach (var item in Model.EnrollmentList)
{
<li> @item.EnrollmentID</li>
<li> @item.CourseID</li>
<
}