所以我試圖在我的一個視圖中使用視圖模型,但我得到了一個InvalidOperationException:傳遞給 ViewDataDictionary 的模型項是“SchoolProject.Models.Student”型別,但是這個 ViewDataDictionary 實體需要一個“SchoolProject”型別的模型項.ViewModels.StudentViewModel'。
這是形成視圖模型的模型:
學生.cs
公共課學生{
[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; }
}
課程.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);
}
最后,觀點:
@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>
我知道我什至沒有在 action 方法中回傳 viewmodel 實體,但我只是不知道該怎么做。我期待著學習如何實作視圖模型來查看。
uj5u.com熱心網友回復:
您應該像這樣將 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
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/498272.html
標籤:C# asp.net-mvc asp.net-mvc-viewmodel
上一篇:從復選框更改為單選按鈕
