[英]Serveral models in one view ASP.net core with EF core
我想使用 ASP.net Core 3.1 和 EF Core 3 在數據庫中創建一個包含兩個表和一個數據圖表的儀表板。
這位老師model class:
public class Teacher
{
[Key]
public Int64 ID { get; set; }
public Sring Name { get; set; }
public int Age { get; set; }
}
這是課程 model class:
public class Course
{
[Key]
public Int64 ID { get; set; }
public Sring Name { get; set; }
public Sring TargetClass { get; set; }
}
ViewModel class 如下:
public class DashboardViewModel
{
public List<Course> Course { get; set; }
public List<Teacher> Teacher { get; set; }
}
索引頁面是:
<h2> Table of Teacher</h2>
<table>
<thead>
<tr>
<th> ID</th>
<th> Name</th>
<th> Age</th>
</tr>
</thead>
<tbody>
@foreach (Teacher item in Model.Teacher)
{
<tr>
<td>
@item.ID
</td>
<td>
@item.Name
</td>
<td>
@item.Age
</td>
</tr>
}
</tbody>
</table>
<h2> Table of Courses</h2>
<table>
<thead>
<tr>
<th> ID</th>
<th> Name</th>
<th> TargetClass</th>
</tr>
</thead>
<tbody>
@foreach (Teacher item in Model.Course)
{
<tr>
<td>
@item.ID
</td>
<td>
@item.Name
</td>
<td>
@item.TargetClass
</td>
</tr>
}
</tbody>
</table>
家controller是:
public class HomeController : Controller
{
private readonly ApplicationDbContext _context;
public HomeController(ApplicationDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
var qry = await _context.Teacher.ToListAsync();
var Teachers = new List<Teacher>(){};
var Courses = new List<Courses>() { };
var Dash = new DashboardViewModel {
Course = Courses,
Teacher = Teachers
};
return View(Dash);
}
嘗試將數據從 qry 變量傳遞到列表時出現問題。 問題:如何將數據從 EF 傳遞到教師列表作為示例?
var qry = _context.Teacher.ToListAsync();
var Teachers = new List<Teacher>(){qry};
沒有轉換錯誤:無法從'System.Threading.Tasks.Task<System.Collections.Generic.List<School.Models.Teacher>>' to 'School.Models.Teacher'
我不能在評論中這樣做,所以我會把它放在這里,然后如果它不太正確,我可以修改答案。 您無需事先創建空列表,只需一次性創建 ViewModel。 正如我認為 jegtugado 試圖建議的那樣,Index() 代碼應該類似於:
public async Task<IActionResult> Index()
{
var Dash = new DashboardViewModel {
Course = await _context.Course.ToListAsync(),
Teacher = await _context.Teacher.ToListAsync()
};
return View(Dash);
}
這是假設您的 DbSet 被稱為教師和課程(但這些通常是復數,所以請仔細檢查)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.