如果有個需求,希望一個 View 能顯示不同的 Domain Model 類別的資料,該怎麼做呢…
那就自訂一個 ViewModel 吧!
Steps:
1. Model: 自訂 IndexViewModel.cs
2. Controller: 在 Controller 把想要呈現資料的物件 (IndexViewModel) 準備好,並傳給View。
3. View: 在View設定@model 的類別為它 (IndexViewModel)
View
@model ModelExample.Models.IndexViewModel
@{ Layout = null; }
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div style="float:left;">
<table border="1">
<tr>
<th>
@Html.LabelFor(m =>m.Students[0].Identity)
</th>
<th>
@Html.LabelFor(m => m.Students[0].FullName)
</th>
</tr>
@foreach (var student in this.Model.Students)
{
<tr>
<td>@student.Identity</td>
<td>@student.FullName</td>
</tr>
}
</table>
</div>
<div style="float:left">
<table border="1">
<tr>
<th>
@Html.LabelFor(m => m.Teachers[0].Identity)
</th>
<th>
@Html.LabelFor(m => m.Teachers[0].FullName)
</th>
</tr>
@foreach (var teacher in this.Model.Teachers)
{
<tr>
<td>@teacher.Identity</td>
<td>@teacher.FullName</td>
</tr>
}
</table>
</div>
</body>
</html>
</html>
Controller
namespace ModelExample.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
List<Student> students = new List<Student>();
for (int i = 0; i < 25; i++)
{
Student student = new Student();
student.Identity = i;
student.FullName = string.Format("Student-{0}",i.ToString().PadLeft(2,'0'));
students.Add(student);
}
List<Teacher> teachers = new List<Teacher>();
for (int i = 0; i < 25; i++)
{
Teacher teacher = new Teacher();
teacher.Identity = i;
teacher.FullName = string.Format("Teacher-{0}", i.ToString().PadLeft(2, '0'));
teachers.Add(teacher);
}
IndexViewModel vm = new IndexViewModel();
vm.Students = students;
vm.Teachers = teachers;
return View(vm);
}
}
}
Model
IndexViewModel
namespace ModelExample.Models
{
public class IndexViewModel
{
public List<Student> Students { get; set; }
public List<Teacher> Teachers { get; set; }
}
}
}
Student
namespace ModelExample.Models
{
public class Student
{
public int Identity { get; set; }
public string FullName { get; set; }
}
}
}
namespace ModelExample.Models
{
public class Teacher
{
public int Identity { get; set; }
public string FullName { get; set; }
}
}
}
https://www.youtube.com/watch?v=4os5xejpJv0