在具有動態 ExpandoObject 的檢視中使用多個模型

ExpandoObject(System.Dynamic 名稱空間)是新增到 .Net Framework 4.0 的類。此類允許我們在執行時動態新增和刪除物件的屬性。通過使用 Expando 物件,我們可以將模型類新增到動態建立的 Expando 物件中。以下示例說明了如何使用此動態物件。

師生模特:

public class Teacher  
{  
    public int TeacherId { get; set; }    
    public string Name { get; set; }  
} 

public class Student  
{  
    public int StudentId { get; set; }  
    public string Name { get; set; }  
}

教師和學生列表方法:

public List<Teacher> GetTeachers()  
{  
    List<Teacher> teachers = new List<Teacher>();  
    teachers.Add(new Teacher { TeacherId = 1, Name = "Teacher1" });  
    teachers.Add(new Teacher { TeacherId = 2, Name = "Teacher2" });  
    teachers.Add(new Teacher { TeacherId = 3, Name = "Teacher3" });  
    return teachers;  
}   

public List<Student> GetStudents()  
{  
    List<Student> students = new List<Student>();  
    students.Add(new Student { StudentId = 1, Name = "Student1"});  
    students.Add(new Student { StudentId = 2, Name = "Student2"});  
    students.Add(new Student { StudentId = 3, Name = "Student3"});  
    return students;  
}

控制器(使用動態模型):

public class HomeController : Controller  
{  
    public ActionResult Index()  
    {  
        ViewBag.Message = "Hello World";  
        dynamic mymodel = new ExpandoObject();  
        mymodel.Teachers = GetTeachers();  
        mymodel.Students = GetStudents();  
        return View(mymodel);  
    }  
}

檢視:

@using ProjectName ; // Project Name  
@model dynamic  
@{  
    ViewBag.Title = "Home Page";  
}  
<h2>@ViewBag.Message</h2>  

<h2>Teacher List</h2>  

<table>  
    <tr>  
        <th>Id</th>    
        <th>Name</th>  
    </tr>  
    @foreach (Teacher teacher in Model.Teachers)  
    {  
        <tr>  
            <td>@teacher.TeacherId</td>  
            <td>@teacher.Name</td>  
        </tr>  
    }  
</table>  

<h2>Student List</h2>  

<table>  
    <tr>  
        <th>Id</th>  
        <th>Name</th>  
    </tr>  
    @foreach (Student student in Model.Students)  
    {  
        <tr>  
            <td>@student.StudentId</td>   
            <td>@student.Name</td>  
        </tr>  
    }  
</table>