Return Multiple Models in Single View in MVC3

To further explore MVC, today I will share one of the interesting facts about MVC 3 to use multiple models in a single view.

I believe this is one of the interesting facts about MVC, that may be used on a regular basis. Because in today's world we generally don't keep data in a single place/model.
 
So let's go.

To move on I'd like to share a little bit about Model-View-Controller (MVC) with excerpts.

Controller

Controllers are the heart of MVC. A controller handles some of the main work of the application, such as:

  • It handles the User Input.
  • It handles the User Interaction.
  • It reads the data from the View.
  • Then it sends the data read to the Model.

In a simpler manner you can say that it receives the request from the user and sends it to the Model, and then the Model retrieves the related data from the database and sends the result to the View. A controller can be associated with multiple view, in other words we can define multiple actions in the controller and show whichever view is associated with the action. It is similar to the Business Layer of a 3-tier architecture. It is the main part of the MVC architecture.

View

View is simply used to display the data; it is the Graphical Data Representation. "Model sends the output to the View then the View displays the data to the end user", so it works like a bridge between the Model and the End User. Often the views are created from the model data.

Model

A Model handles the logic for the application data; it implements the Data Domain logic. A Model is associated with Views and the Controller. It produces updated output on the view. Often model objects retrieve data from the database and store the data to the database. The Database Connection is part of the model and it provides the output requested by the user.
 
A typical diagram of MVC

Return-Multiple-Models-in-single-View-in-MVC3-1.jpg
Now we move ahead and discuss the code agenda of this article.

Step 1

I've created a Model class named "GuestResponse" having the code snippet:

Return-Multiple-Models-in-single-View-in-MVC3-2.jpg 

Step 2

Whenever we hit any URL in a browser it generally goes to a controller and the controller performs its action and returns its model to the view. I have HomeController for this purpose and the code shown in the following image:

Return-Multiple-Models-in-single-View-in-MVC3-3.jpg

Let's discuss the code snippet in the image given above.
 
I first created an object of the ParentModel class like:

  1. ParentModel objParent = new ParentModel();

I then created an object of the GuestResponse model class, that is of a List type having some values, as in the following code snippet:

  1. List<GuestResponse> objGuestResponse = new List<GuestResponse>();  
  2. objGuestResponse.Add(new GuestResponse { Name = "Sachin Kalia", Email = "[email protected]", WillAttend = true });  
  3. objGuestResponse.Add(new GuestResponse { Name = "Ravish Sindhwani", Email = "[email protected]", WillAttend = true });  
  4. objGuestResponse.Add(new GuestResponse { Name = "Dhananjay Kumar", Email = "[email protected]", WillAttend = true }); 

And passed its object to "ParentModel" as in the following:

  1. objParent.GuestResponse = objGuestResponse;
The same flow for the "GuestCheck" model class that is also of List type having some values as in the following in code snippet:

  1. List<GuestCheck> objGuestCheck = new List<GuestCheck>();   
  2. objGuestCheck.Add(new GuestCheck { GuestName = "Sachin Kalia", GuestPhone = "9911635975" });  
  3. objGuestCheck.Add(new GuestCheck { GuestName = "Ravish Sindhwani", GuestPhone = "7666666786" });  
  4. objGuestCheck.Add(new GuestCheck { GuestName = "Dhananjay Kumar", GuestPhone = "7667877786" });   

And passed its object to "ParentModel" as in the following:

  1. objParent.GuestCheck = objGuestCheck;
Now to move ahead and create an object of ParentModel, the following image is self-descriptive:

Return-Multiple-Models-in-single-View-in-MVC3-4.jpg

Step 3

The next step is to create a View named "RsvpForm.cshtml" with the following code snippet:

  1. @using (Html.BeginForm())  
  2. {    
  3.         <h2 style="background-color:Lime" color:"red">EmpRegistration</h2>       
  4.      foreach (var item in Model)  
  5.      {  
  6.     <tr>  
  7.        @for (int i = 0; i < @item.GuestResponse.Count; i++)  
  8.        {           
  9.            <td>  
  10.           <table><tr>  
  11.           <td> @item.GuestResponse[i].Name  @item.GuestResponse[i].Email   @item.GuestCheck[i].GuestPhone ||</td>  
  12.           @Html.Raw(HttpUtility.HtmlEncode(Environment.NewLine))  
  13.           </tr></table>  
  14.         </td>  
  15.        }  
  16.             @*@Html.DisplayFor(modelItem =>  item.GuestResponse[1].Email.ToString())*@  
  17.         </tr>  
  18.    }  
  19. } 

@model IEnumerable<MVCSample.Models.ParentModel>: If you notice at this line you will examine this model is of IEnumerable type that we've returned from HomeController class.
 
And another very important fact is related to the Model collection at the time of iteration in a foreach loop, as in:

Return-Multiple-Models-in-single-View-in-MVC3-5.jpg

It gives you the collection of both model classes, that we look for.
 
Step 4
 
Now to run you application and press F5 .You will see the following image:

Return-Multiple-Models-in-single-View-in-MVC3-6.jpg

Ignore this and paste the following URL in your browser window: http://localhost:60346/Home/Rsvpform
 
The output will be:

Return-Multiple-Models-in-single-View-in-MVC3-7.jpg
I tried to keep this simple to make this easier to understand.


Similar Articles