如何在一个视图中使用多个模型

时间:2015-07-16 08:55:31

标签: c# asp.net-mvc razor

public class Student
    {
      public string Name;
      public int Age;
    }

 List<Student> StudentList = new List<Student>
 {
   new Student{ Name = "Handri", Age = 8 },
   new Student{Name = "Jon Galloway", Age = 10},
   new Student{ Name = "Scott Hanselman", Age = 9}
 };

public class Teacher
  {
  public string Name;
  public int Age;
  }

 List<Teacher> TeacherList = new List<TeacherList>
 {
   new TeacherList { Name = "Jhon", Age = 30 },
   new TeacherList {Name = "JANE", Age = 25},
   new TeacherList { Name = "Peter", Age = 27}
 };

我需要在我的模型中使用多个视图;

............................................... .................................................. .................................................. .......

1 个答案:

答案 0 :(得分:0)

使用元组

Tuple对象是一个不可变的,固定大小和有序的序列对象。它是一种具有特定数量和元素序列的数据结构。 .NET框架支持最多七个元素的元组。

使用这个元组对象,我们可以将多个模型从控制器传递给视图。

控制器代码

public ActionResult IndexTuple()
{
    ViewBag.Message = "Welcome to my demo!";
    var tupleModel = new Tuple<List<Teacher>, List<Student>>(GetTeachers(), GetStudents());
    return View(tupleModel);
}

View Code

@using MultipleModelInOneView;
@model Tuple <List<Teacher>, List <Student>>
@{
    ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2> 
<p><b>Teacher List</b></p>
<table>
    <tr>
        <th>Id</th>
        <th>Code</th>
        <th>Name</th>
    </tr>
    @foreach (Teacher teacher in Model.Item1)
    {
        <tr>
            <td>@teacher.TeacherId</td>
            <td>@teacher.Code</td>
            <td>@teacher.Name</td>
        </tr>
    }
</table>
<p><b>Student List</b></p>
<table>
    <tr>
        <th>Id</th>
        <th>Code</th>
        <th>Name</th>
        <th>Enrollment No</th>
    </tr>
    @foreach (Student student in Model.Item2)
    {
        <tr>
            <td>@student.StudentId</td>
            <td>@student.Code</td>
            <td>@student.Name</td>
            <td>@student.EnrollmentNo</td>
        </tr>
    }
</table>

更多细节可参考此链接 http://www.c-sharpcorner.com/UploadFile/ff2f08/multiple-models-in-single-view-in-mvc/