MVC Imp
MVC Imp
The following are the model definitions for the Teacher and Student classes.
The following are the methods that help us to get all the teachers and students.
There are many ways to use multiple models with a single view. Here I will explain ways one by one.
Controller Code
We can define our model as dynamic (not a strongly typed model) using the @model dynamic keyword.
View Code
@using MultipleModelInOneView;
@model dynamic
@{
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>
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.
In the above example, we have the required View model with two properties. This ViewModel is passed to
the view as a model. To get intellisense in the view, we need to define a strongly typed view.
Controller code
@using MultipleModelInOneView;
@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>