在视图中使用视图模型有问题



所以我试图在我的一个视图中使用视图模型,但我得到一个InvalidOperationException:传入ViewDataDictionary的模型项目是类型'SchoolProject.Models。但是这个ViewDataDictionary实例需要一个类型为'SchoolProject.ViewModels.StudentViewModel'的模型项。

这是我的模型,形成视图模型:

Student.cs

public class Student{

[Key]
public int StudentID { get; set; }
[Required]
public string Name { get; set; }
public string Surname { get; set; }
public int? Age { get; set; }
public ICollection<Enrollment> Enrollments { get; set; }

}

Course.cs

public class Course
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CourseID { get; set; }
public string? Title { get; set; }
public int Credit { get; set; }
public ICollection<Enrollment> Enrollments { get; set; }

}

和StudentViewModel:

public class StudentViewModel
{
public Student Student { get; set; }
public List<Course> Courses { get; set; }
}

动作方法:

public async Task<IActionResult> Details(int id)
{

var student = await _context.Student.FirstOrDefaultAsync(m => m.StudentID == id);
return View(student);
}

最后,view:

@model SchoolProject.ViewModels.StudentViewModel
@{
IEnumerable<Course> courses = ViewData["Courses"] as IEnumerable<Course>;

}

<html>
<body>
<h1 style="text-align : left" >Öğrenci Bilgileri</h1>
<br></br>
<br></br>
<p class="bx" style=" display : inline-block">Öğrenci Adı : </p>
<p class="bx1" style="display : inline-block"> @Html.DisplayFor(model => model.Student.Name)</p>
<br></br>
<p class="bx" style=" display : inline-block">Öğrenci Soyadı : </p>
<p class="bx1" style="display : inline-block"> @Html.DisplayFor(model => model.Student.Surname)</p>
<br></br>
<p class="bx" style=" display : inline-block">Öğrenci Yaşı : </p>
<p class="bx1" style="display : inline-block"> @Html.DisplayFor(model => model.Student.Age)</p>
<h1 style="position : absolute; top : 80px; left: 700px"> Öğrencinin Aldığı dersler</h1>
<div style="position : absolute; left : 600px; top: 100px" class="vl"></div>
@foreach(var ders in Model.Courses)
{
@Html.DisplayFor(modelItem => ders.CourseID)
}
<table class="table">
<thead>
<tr>
<td>
Dersler
</td>
<td>
Kredi
</td>
</tr>
</thead>
<tbody>
@foreach(var course in Model.Courses)
{
<tr>
<td>
@Html.DisplayFor(model => course.Title)
</td>
<td>
@Html.DisplayFor(model => course.Credit)
</td>
</tr>
}
</tbody>
</table>
</body>

我知道我甚至不返回一个视图模型实例在动作方法,但我只是根本不知道我怎么能做到这一点。我期待着学习如何实现viewmodels来查看。

你应该像这样将StudentViewModel传递给视图:

var student = await _context.Student.FirstOrDefaultAsync(m => m.StudentID == id);
var cousre = await _context.course(/*on related student column*/).ToListAsync();    
return View(  new StudentViewModel{
Student = student , 
Courses  = cousre
});

最新更新