在具有动态 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>