There can a situation in your web-application when you need to show or pass multiple models in a single view in C# Razor using ASP.NET MVC, so in this article, I am going to explain about different ways which can help you in passing multiple models data in a view.

There are many ways of using multiple models in a view, most frequently used are given below:

  • Dynamic
  • ViewData
  • ViewBag
  • PartialView
  • ViewModel
  • Tuple

All of the above ways work well and will help you to show multiple models data in a Single view, but you would have to select them, according to your need and requirement, so to better understand it, let's take an example of each of the above solution one by one.

So, to understand each one of them one by one, we will use a common example, suppose we need to show data of two Models Students and Faculty in a single C# Razor view.

public class Faculty
{  
    public int FacultyId{ get; set; }    
    public string Name { get; set; }  
}   
  
public class Student  
{  
    public int StudentId { get; set; }      
    public string Name { get; set; }  
    public string RollNo{ get; set; }  
} 

Now, let's create a sample Repository to return the sample data, which we would need in order to complete the above requirement.

 public class RespositoryClass
    {
        public static List<Student> GetStudents()
        {
            return new List<Student>{ new Student() { StudentId = 1, Name = "Jai",RollNo=12 },
                 new Student() { StudentId = 2, Name = "James" ,RollNo=13},
                 new Student() { StudentId = 3, Name = "John",RollNo=14 }
                 };
        }
        public static List<Faculty> GetFaculty()
        {
            return new List<Faculty> {
                new Faculty () {  FacultyId = 1, Name = "Joseph john"},
                new Faculty () {  FacultyId = 2, Name = "Sam"},
                new Faculty () {  FacultyId = 3, Name = "Stephen miller" },
                
                 };
        }
    }

Now to get started, you would have to create a Project in your Visual Studio, open our Visual Studio IDE, create a new project, by navigating to "File"-> "New"-> "Project".

Select "Web" in the left pane and "ASP.NET Web application" in the right pane, provide a name for your web application(In my example it's "MultipleModelSingleView"), Click "OK".

Create the above Models and Repository class as explained & navigate to HomeController -> Index ActionMethod -> right click and click "Go to View", if there is some code/html, remove it.

In the Index.cshtml View, you can place all the possible ways links

        <div>
            <h3>Links of various ways to pass multiple data example</h3>
            <a href="/Home/DynamicDemo">Dynamic Demo</a>
            <br />
            <br />
            <a href="/Home/UsingViewData">ViewData Demo</a>
            <br />
            <br />
            <a href="/Home/ViewBagDemo">ViewBag Demo</a>
            <br />
            <br />
            <a href="/Home/PartialViewDemo">PartialView Demo</a>           
            <br />
            <br />
            <a href="/Home/ViewModelDemo">ViewModel Demo</a>
            <br />
            <br />
            <a href="/Home/TupleDemo">Tuple Demo</a>
        </div>

Passing multiple models data in a single view using Dynamic Model

The ExpandoObject class enables us to add and delete members at runtime.So If we want to build up an object to work with on the fly at runtime then we can use Expando Object.Let's see how can we use ExpandoObject with Multiple Models.

So, go to your HomController, and add the below C# ActionMethod

        public ActionResult DynamicDemo()
        {
            dynamic myDynamicmodel = new System.Dynamic.ExpandoObject();
            myDynamicmodel.Students = RespositoryClass.GetStudents();
            myDynamicmodel.Faculty = RespositoryClass.GetFaculty();
            return View(myDynamicmodel);
        }

Now, add a view for it, and use the below code to show data

@model dynamic
@{
    ViewBag.Title = "Dynamic Page";
}
<h2>Dynamic Models</h2>

<h3>Student List</h3>

<div class="row">
    <div class="col-lg-6">
        <table class="table table-responsive table-bordered">
            <thead>
                <tr>
                    <th>Student ID</th>
                    <th>Student Name</th>
                    <th>Roll No.</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model.Students)
                {
                    <tr><td>@item.StudentId</td><td>@item.Name</td> <td>@item.RollNo</td></tr>
                }
            </tbody>
        </table>
    </div>
</div>
<h3>Faculty List</h3>

<div class="row">
    <div class="col-lg-6">
        <table class="table table-responsive table-bordered">
            <thead>
              <tr>
                  <th align="center">Faculty Id</th>
                  <th align="center">Faculty Name</th>
                  </tr>
            </thead>
            <tbody>
                @foreach (var item in Model.Faculty)
                {
                    <tr><td>@item.FacultyId</td><td>@item.Name</td></tr>
                }
            </tbody>
        </table>
    </div>
</div>

Now build your project and run it in the browser, navigate to the URL "http://localhost:57491/Home/DynamicDemo", you will see output as below

passing-dynamic-multiple-model-in-single-view-asp-net-mvc-min.png

As you can see in the above image, we have both the Models data in the view, which was combined in Dynamic Model using System.Dynamic.ExpandoObject().

Passing Multiple Models in a View using View Data

ViewData is used to transfer data from the controller to the view. ViewData is a dictionary object that may be accessible using a string as the key. Using ViewData, we can pass any object from the controller to the view.

Values stored in ViewData require typecasting to their datatype in view. The values in ViewData are accessible using a key.

So to use this for multiple models, create a new ActionMethod

public ActionResult UsingViewData()
{    
    //ViewData for Students list
    ViewData["Students"] = RespositoryClass.GetStudents();
    //ViewData for Faculty list
    ViewData["Faculty"] = RespositoryClass.GetFaculty();
    return View();
}

In your View

@using MultipleModelSingleView.Models
@{
    ViewBag.Title = "Using ViewData";
}

<h2>Using ViewData for multiple models</h2>
<div class="row">
    <div class="col-lg-6">
        <table class="table table-responsive table-bordered">
            <thead>
                <tr>
                    <th>Student ID</th>
                    <th>Student Name</th>
                    <th>Roll No.</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in ViewData["Students"] as List<StudentFaculty.Student>)
                {
                <tr><td>@item.StudentId</td><td>@item.Name</td> <td>@item.RollNo</td></tr>
                }
            </tbody>
        </table>
    </div>
</div>
<h3>Faculty List</h3>

<div class="row">
    <div class="col-lg-6">
        <table class="table table-responsive table-bordered">
            <thead>
                <tr>
                    <th align="center">Faculty Id</th>
                    <th align="center">Faculty Name</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in ViewData["Faculty"] as List<StudentFaculty.Faculty>)
                {
                <tr><td>@item.FacultyId</td><td>@item.Name</td></tr>
                }
            </tbody>
        </table>
    </div>
</div>

Output:

passing-multiple-model-in-single-view-asp-net-mvc-using-viewdata-min.png

Passing Multiple Models in a View using ViewBag

ViewBag is similar to ViewData and is also used to transfer data from the controller to the view. ViewBag is a dynamic property. ViewBag is just a wrapper around the ViewData.

It is a dynamic property which comes in ControllerBase class that is why it doesn’t require typecasting for the datatype.

Let's create ActionMethod for it in HomeController

 public ActionResult ViewBagDemo()
        {          
            ViewBag.Students = RespositoryClass.GetStudents();
            ViewBag.Faculties = RespositoryClass.GetFaculty();
            return View();
        }

In View

@{
    ViewBag.Title = "ViewBag Demo";
}

<h2>Using ViewBag for multiple models</h2>

<div class="row">
    <div class="col-lg-6">
        <table class="table table-responsive table-bordered">
            <thead>
                <tr>
                    <th>Student ID</th>
                    <th>Student Name</th>
                    <th>Roll No.</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in ViewBag.Students)
                {
                    <tr><td>@item.StudentId</td><td>@item.Name</td> <td>@item.RollNo</td></tr>
                }
            </tbody>
        </table>
    </div>
</div>
<h3>Faculty List</h3>

<div class="row">
    <div class="col-lg-6">
        <table class="table table-responsive table-bordered">
            <thead>
                <tr>
                    <th align="center">Faculty Id</th>
                    <th align="center">Faculty Name</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in ViewBag.Faculties)
                {
                    <tr><td>@item.FacultyId</td><td>@item.Name</td></tr>
                }
            </tbody>
        </table>
    </div>
</div>

Output is same as above both models get's included.

Passing Multiple Models in a View using PartialView

This approach is a little bit different than the above approach of showing multiple models using ViewBag as in this we would have to create two partial views and we can pass the ViewBag data as model in the partial view.

So, keeping the same ActionMethod, just changing it's name in Controller

 public ActionResult PartialViewDemo()
        {          
            ViewBag.Students = RespositoryClass.GetStudents();
            ViewBag.Faculties = RespositoryClass.GetFaculty();
            return View();
        }

Now, create a view for PartialViewDemo and then you need to call partial view with Model(here we are using ViewBag to pass model data, you can use ViewModel also, which I will explain in next section)

So here is the Main View

@using MultipleModelSingleView.Models
@{
    ViewBag.Title = "PartialView Demo";
}

<h2>PartialView Demo for multiple models</h2>

@{ Html.RenderPartial("_Students", (IEnumerable<StudentFaculty.Student>)ViewBag.Students); }

@{ Html.RenderPartial("_Faculties", (IEnumerable<StudentFaculty.Faculty>)ViewBag.Faculties); }

 Now, let's add the Partial View(_Students and _Faculties).

_Students.cshtml

Right click in Controller ActionMethod, and then partial View as below image

_students-partial-view-for-multiple-models-min.png

@model IEnumerable<MultipleModelSingleView.Models.StudentFaculty.Student>
<h3>Student List</h3>
<div class="row">
    <div class="col-lg-6">
        <table class="table table-responsive table-bordered">
            <thead>
                <tr>
                    <th>Student ID</th>
                    <th>Student Name</th>
                    <th>Roll No.</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model)
                {
                    <tr><td>@item.StudentId</td><td>@item.Name</td> <td>@item.RollNo</td></tr>
                }
            </tbody>
        </table>
    </div>
</div>

_Faculties.cshtml

Right click in Controller ActionMethod, and then partial View as below image

faculty-partial-view-mvc-min.png

@model IEnumerable<MultipleModelSingleView.Models.StudentFaculty.Faculty>

<h3>Faculty List</h3>

<div class="row">
    <div class="col-lg-6">
        <table class="table table-responsive table-bordered">
            <thead>
                <tr>
                    <th align="center">Faculty Id</th>
                    <th align="center">Faculty Name</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model)
                {
                    <tr><td>@item.FacultyId</td><td>@item.Name</td></tr>
                }
            </tbody>
        </table>
    </div>
</div>

Output will show you both data of both Models.

Passing Multiple Models in a View using ViewModel

ViewModel is a class, created by user in which we can define the properties or list of models to show in View. ViewModel is a pattern that allow us to have multiple models as a single class. It contains properties of entities exactly need to be used in a view. ViewModel should not have methods.

So for our example, If we want to create a View where we want to display list of Students and Faculties then we will create our View Model (StudentFacultyViewModel.cs) as below

public class StudentFacultyViewModel
    {       
        public List<Student> AllStudents { get; set; }
        public List<Faculty> AllFaculties { get; set; }
    }

Now, create a ActionMethod to fill data in above ViewModel and pass it to view.

public ActionResult UsingViewModel()
        {
            
            StudentFacultyViewModel vm = new StudentFacultyViewModel();
            vm.AllStudents = RespositoryClass.GetStudents();
            vm.AllFaculties = RespositoryClass.GetFaculty();
            return View(vm);
        }

In next step, we need to create View which accepts model of type StudentFacultyViewModel & loop data of each Model to display it.

@model MultipleModelSingleView.Models.StudentFacultyViewModel
@{
    ViewBag.Title = "Using ViewModel";
}

<h2>Multiple models using ViewModel</h2>

<h3>Student List</h3>
<div class="row">
    <div class="col-lg-6">
        <table class="table table-responsive table-bordered">
            <thead>
                <tr>
                    <th>Student ID</th>
                    <th>Student Name</th>
                    <th>Roll No.</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model.AllStudents)
                {
                    <tr><td>@item.StudentId</td><td>@item.Name</td> <td>@item.RollNo</td></tr>
                }
            </tbody>
        </table>
    </div>
</div>


<h3>Faculty List</h3>

<div class="row">
    <div class="col-lg-6">
        <table class="table table-responsive table-bordered">
            <thead>
                <tr>
                    <th align="center">Faculty Id</th>
                    <th align="center">Faculty Name</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model.AllFaculties)
                {
                    <tr><td>@item.FacultyId</td><td>@item.Name</td></tr>
                }
            </tbody>
        </table>
    </div>
</div>


That's it for using the ViewModel, we can now loop in each Model values as shown in the above view, you will get the data.

Passing Multiple Models in a View using Tuple

A Tuple object is an immutable, fixed-size and ordered sequence object. Each object in tuple is being of a specific type. Tuple class was introduced in .NET Framework 4.0.

Tuple allows us to group multiple kind of data types. So, using tuple object we can pass multiple models from the controller to the view.

To use this method, create a ActionMethod as below

 public ActionResult UsingTuple()
        {            
            var tupleModel = new Tuple<List<StudentFaculty.Student>, List<StudentFaculty.Faculty>>(RespositoryClass.GetStudents(), RespositoryClass.GetFaculty());
            return View(tupleModel);
        }

In your View, you need to define tuple classes as model and loop through each data of list.

@using MultipleModelSingleView.Models

@model Tuple<List<StudentFaculty.Student>, List<StudentFaculty.Faculty>>
@{
    ViewBag.Title = "Using Tuple";
}

<h2>Multiple models using Tuple</h2>

<h3>Student List</h3>
<div class="row">
    <div class="col-lg-6">
        <table class="table table-responsive table-bordered">
            <thead>
                <tr>
                    <th>Student ID</th>
                    <th>Student Name</th>
                    <th>Roll No.</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model.Item1)
                {
                    <tr><td>@item.StudentId</td><td>@item.Name</td> <td>@item.RollNo</td></tr>
                }
            </tbody>
        </table>
    </div>
</div>


<h3>Faculty List</h3>

<div class="row">
    <div class="col-lg-6">
        <table class="table table-responsive table-bordered">
            <thead>
                <tr>
                    <th align="center">Faculty Id</th>
                    <th align="center">Faculty Name</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model.Item2)
                {
                    <tr><td>@item.FacultyId</td><td>@item.Name</td></tr>
                }
            </tbody>
        </table>
    </div>
</div>

That's it, these are the most widely used possible ways to show Multiple Models in single View, here is the complete gif image demo.

multiple-models-in-one-view-single-view-asp-net-mvc-min.gif

Feel free to share your view on this article using the comments, section or ask any query related to this.

You may also like to read:

Tuples in C# With an example

Rich Text Editor in ASP.NET MVC