Multiple Models In Single View Using Entity Framework

If you are new to MVC, please refer to the following links of my previous articles covering the basic concepts of MVC.

In many forms/pages, often, we are required to send the data from two tables onto one page. We will achieve the task with a real-world example.

Task Description

In this task, we will display the details of a particular student in a Master Detail format.

First, we'll fetch the student's details, then fetch the student's exam data. We are going to use Entity Framework - Code First approach.

This task can be called Master Detail View because the master is student's detail and the detail is student's exam marks detail.

The Student Result table will display the following details.

Student Detail Table

  1. GR No.
  2. Student Name
  3. Class
  4. Batch
  5. Date of Birth

Student Result Table

  1. StudentResultID
  2. StudentID
  3. Subject
  4. Exam Mark
  5. Obtained Mark
  6. Remarks

Step by Step Implementation

First, create a project called “StudentResult-EF”.

Multiple Model In Single View Using Entity Framework 
 
Multiple Model In Single View Using Entity Framework 

In the above dialog box, select MVC and change the authentication from "Individual User Accounts" to "No Authentication". Click the OK button.

Multiple Model In Single View Using Entity Framework 

Your Solution Explorer will look like the following.

Multiple Model In Single View Using Entity Framework 

First, create a table structure called “tblStudents”.

  1. Create Table tblStudents(  
  2. StudentID int primary key identity(1,1) ,  
  3. StudentName varchar(100) null,  
  4. GRNO varchar(50) null,  
  5. Class varchar(50) null,  
  6. Batch varchar(50) null,  
  7. DOB varchar(50) null  
  8. )  

Create a table structure called “tblStudentResults”.

  1. Create Table tblStudentResults(  
  2. StudentResultID int primary key identity(1,1) ,  
  3. StudentID int null,  
  4. SubjectTitle varchar(50) null,  
  5. ExamMark int null,   
  6. ObtainedMark int null,  
  7. Remarks varchar(100) null  
  8. )  

Add sample records to tblStudents.

  1. insert into tblStudents (StudentName,GRNO,Class,Batch,DOB) values('Ganesh Bansal','101','10th','A','2018-12-10')  
  2. insert into tblStudents (StudentName,GRNO,Class,Batch,DOB) values('Ashish Kalla','102','10th','A','2010-12-10')  
  3. insert into tblStudents (StudentName,GRNO,Class,Batch,DOB) values('Suhana Kalla','103','10th','A','2011-12-10')  
  4. insert into tblStudents (StudentName,GRNO,Class,Batch,DOB) values('Rajesh Bohra','104','10th','A','2017-12-10')  

Add sample records to tblStudentResults.

  1. insert into tblStudentResults  
  2. (StudentID,SubjectTitle,ExamMark,ObtainedMark,Remarks)  
  3. values(1,'Maths',100,55,'Pass')  
  4.   
  5. insert into tblStudentResults  
  6. (StudentID,SubjectTitle,ExamMark,ObtainedMark,Remarks)  
  7. values(1,'Science',100,70,'Pass')  
  8.   
  9. insert into tblStudentResults  
  10. (StudentID,SubjectTitle,ExamMark,ObtainedMark,Remarks)  
  11. values(1,'Hindi',100,38,'Pass')  
  12.   
  13. insert into tblStudentResults  
  14. (StudentID,SubjectTitle,ExamMark,ObtainedMark,Remarks)  
  15. values(1,'Marathi',100,40,'Pass')  

As we are going to use Entity Framework - Code First approach, switch to Visual Studio and right-click on Models folder to add an ADO.NET Entity Data Model item.

Multiple Model In Single View Using Entity Framework 

The below image shows the process of inserting ADO.NET Entity data model from the Data tab. Let us name it as “StudentModel”.

Multiple Model In Single View Using Entity Framework 

In the following dialog box, select "Code First from database".

Multiple Model In Single View Using Entity Framework 

In the following screenshot, given is the explanation.

  1. You have to check and get your existing connection.
  2. If there is no desired or existing connection, then you have to click the option number 2.

Here, set or establish your connection.

Multiple Model In Single View Using Entity Framework 

I had clicked on the number 2 choice of the button.

Multiple Model In Single View Using Entity Framework 

I have filled the above form with the following choices.

Multiple Model In Single View Using Entity Framework 

After filling the form as above, you will get the following screenshot.

Multiple Model In Single View Using Entity Framework 

In number 1, I have given a Connection String named “StudentDbContext”.

Multiple Model In Single View Using Entity Framework 

As you clicked on the FINISH button, you can see the left bottom side status message “Adding EntityFrameWork 6.1.3" because the Entity Framework was not already added to this project.

Multiple Model In Single View Using Entity Framework 

Now, switch to the Solution Explorer. You can see the models have been added to your Models folder.

Multiple Model In Single View Using Entity Framework 

As of now, our basic model was created successfully. Now, it's time to create a ViewModel. Why we used ViewModel is because it will display data of both the tables together.

Again, right-click the model on Solution Explorer to create a ViewModel called “ResultViewModel”.

Multiple Model In Single View Using Entity Framework 

Update the following code in the ViewModel file called “ResultViewModel.cs”.

Code of ResultViewModel.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace StudentResult_EF.Models  
  7. {  
  8.     public class ResultViewModel  
  9.     {  
  10. //Student Detail Model   
  11.         public tblStudent _studentDetail { get; set; }  
  12.   
  13.         //Student Exam Result List Model   
  14.         public List<tblStudentResult> _studentResult { get; set; }  
  15.     }  
  16. }  

In the above ResultViewModel.cs code, you can see we have joined two models in one. This is only for viewing purpose; that's why it is called ViewModel.

Switch back to the Solution Explorer to add a new Controller called “StudentResult”.

Multiple Model In Single View Using Entity Framework 
 
Multiple Model In Single View Using Entity Framework
 
Multiple Model In Single View Using Entity Framework 

Now, double-click on StudentController and create a result ActionMethod.

  1. [HttpGet]  
  2. public ActionResult result(Int32? id)  
  3. {  
  4.     //create object of ADO.Net Entity Data Model Code First  
  5.     var db = new StudentModel();  
  6.   
  7.     //Get Student detail as per student ID  
  8.     var student = (from a in db.tblStudents  
  9.                    where a.StudentID == id  
  10.                    select a).FirstOrDefault();  
  11.   
  12.     //Get Result Exam marks detail as per student ID  
  13.     var result = (from a in db.tblStudentResults  
  14.                   where a.StudentID == id  
  15.                   select a).ToList();  
  16.   
  17.     //Output set to ViewModel  
  18.     var model = new ResultViewModel { _studentDetail = student, _studentResult = result};  
  19.   
  20.     return View(model);  
  21. }  

Right-click on the Controller and select "Add View…".

Multiple Model In Single View Using Entity Framework 

In the following screenshot, I have selected the following things.

  1. View Name : result (a result.cshtml file will be created).
  2. Template: Details (the type of template to create.)
  3. Model Class: Result

    Multiple Model In Single View Using Entity Framework

View code : result.cshtml

  1. @model StudentResult_EF.Models.ResultViewModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "Student Result";  
  5. }  
  6.   
  7. <style>  
  8.     table, th, td {  
  9.   border: 1px solid black;  
  10. }  
  11. </style>  
  12. <h3>Student Result</h3>  
  13.   
  14. <div>  
  15.     <b>Student Detail</b>  
  16.       <table>  
  17.         <tr>  
  18.             <td>  
  19.                 Student Name<br />  
  20.                 <b>@Model._studentDetail.StudentName</b>  
  21.             </td>  
  22.             <td>  
  23.                 GR No.<br />  
  24.                 <b>@Model._studentDetail.GRNO</b>  
  25.             </td>  
  26.             <td>  
  27.                 Class / Batch<br />  
  28.                 <b>@Model._studentDetail.Class/@Model._studentDetail.Batch</b>  
  29.             </td>  
  30.             <td>  
  31.                 Date of Birth<br />  
  32.                 <b>@Model._studentDetail.DOB</b>  
  33.             </td>  
  34.         </tr>  
  35.     </table>  
  36.     <br />  
  37.     <table>  
  38.         <tr>  
  39.             <td>  
  40.                 <b>Subject</b>  
  41.             </td>  
  42.             <td>  
  43.                 <b>Marks</b>  
  44.             </td>  
  45.             <td>  
  46.                 <b>Obtained</b>  
  47.             </td>  
  48.             <td>  
  49.                 <b>Remarks</b>  
  50.             </td>  
  51.         </tr>  
  52.   
  53.         @foreach (var item in Model._studentResult)  
  54.         {  
  55.         <tr>  
  56.             <td>  
  57.                 @item.SubjectTitle  
  58.             </td>  
  59.             <td>  
  60.                 @item.ExamMark  
  61.             </td>  
  62.             <td>  
  63.                 @item.ObtainedMark  
  64.             </td>  
  65.             <td>  
  66.                 @item.Remarks  
  67.             </td>  
  68.         </tr>  
  69.         }  
  70.     </table>  
  71.       
  72. </div>  
  73. <p>  
  74.     @Html.ActionLink("Edit""Edit"new { /* id = Model.PrimaryKey */ }) |  
  75.     @Html.ActionLink("Back to List""Index")  
  76. </p>  

Output

Multiple Model In Single View Using Entity Framework


Similar Articles