In MVC we cannot pass multiple models from a controller to the single view.
There are a few solution for that problem. But in this article we will use View Model.
Here is the solution:
Let’s say we have Teacher and Student classes.
public class Teacher { public int TeacherId { get; set; } public string Code { get; set; } public string Name { get; set; } } public class Student { public int StudentId { get; set; } public string Code { get; set; } public string Name { get; set; } public string EnrollmentNo { get; set; } }
And those are the methods that help us to get all the teachers and students.
private List<Teacher> GetTeachers() { List<Teacher> teachers = new List<Teacher>(); teachers.Add(new Teacher { TeacherId = 1, Code = "TT", Name = "Student1" }); teachers.Add(new Teacher { TeacherId = 2, Code = "JT", Name = "Student2" }); teachers.Add(new Teacher { TeacherId = 3, Code = "RT", Name = "Studen3" }); return teachers; } public List<Student> GetStudents() { List<Student> students = new List<Student>(); students.Add(new Student { StudentId = 1, Code = "L0001", Name = "Student1", EnrollmentNo = "201404150001" }); students.Add(new Student { StudentId = 2, Code = "L0002", Name = "Student2", EnrollmentNo = "201404150002" }); students.Add(new Student { StudentId = 3, Code = "L0003", Name = "Student3", EnrollmentNo = "201404150003" }); return students; }
ViewModel is nothing but a single class that may have multiple models. It contains multiple models as a property. It should not contain any method.
ViewModel is passed to the view as a model. To get intellisense in the view, we need to define a strongly typed view.
public class ViewModel { public IEnumerable<Teacher> Teachers { get; set; } public IEnumerable<Student> Students { get; set; } }
Controller code
public ActionResult IndexViewModel() { ViewBag.Message = "Teacher & Student List in Single View"; ViewModel mymodel = new ViewModel(); mymodel.Teachers = GetTeachers(); mymodel.Students = GetStudents(); return View(mymodel); }
View code
... @model ViewModel @{ 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.Teachers) { <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.Students) { <tr> <td>@student.StudentId</td> <td>@student.Code</td> <td>@student.Name</td> <td>@student.EnrollmentNo</td> </tr> } </table>