How to Use Multiple Models in One View in ASP.NET MVC

Introduction

In ASP.NET MVC applications, a view is usually strongly typed with one model. However, in real-world applications we often need to display data from multiple tables on the same page.

For example:

  • A Student list

  • A Course list

Both pieces of information may need to appear on the same view page.

Since ASP.NET MVC does not allow multiple models directly in a single view, we solve this problem using a ViewModel.

In this article, we will learn:

  • Why multiple models are needed

  • How to create a ViewModel

  • How to fetch data from SQL Server

  • How to display multiple data sets in a single view

Real-World Example

Imagine a School Management System.

On the dashboard page we want to show:

  • List of Students

  • List of Courses

Since both tables contain different data, we need two models.

Project Structure

Models
   Student.cs
   Course.cs
   DashboardViewModel.cs

Controllers
   HomeController.cs

Views
   Home
      Index.cshtml

Step 1: Create SQL Server Tables

First create tables in SQL Server.

Student Table

CREATE TABLE Students
(
Id INT PRIMARY KEY IDENTITY,
Name NVARCHAR(100),
Age INT
)

Course Table

CREATE TABLE Courses
(
CourseId INT PRIMARY KEY IDENTITY,
CourseName NVARCHAR(100)
)

Insert sample data.

INSERT INTO Students(Name,Age)
VALUES ('Rahul',20),('Neha',22)

INSERT INTO Courses(CourseName)
VALUES ('C#'),('ASP.NET MVC')

Step 2: Create Models

Student Model

Models → Student.cs

public class Student
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int Age { get; set; }
}

Course Model

Models → Course.cs

public class Course
{
    public int CourseId { get; set; }

    public string CourseName { get; set; }
}

These classes represent the database tables.

Step 3: Create ViewModel

Now create a ViewModel.

Models → DashboardViewModel.cs

using System.Collections.Generic;

public class DashboardViewModel
{
    public List<Student> Students { get; set; }

    public List<Course> Courses { get; set; }
}

Explanation

The ViewModel combines multiple models into a single object.

This allows the view to access both:

  • Student data

  • Course data

Step 4: Add Connection String

Open Web.config.

<connectionStrings>
  <add name="dbcon"
       connectionString="Data Source=.;Initial Catalog=SchoolDB;Integrated Security=True"
       providerName="System.Data.SqlClient"/>
</connectionStrings>

This connects the application to SQL Server.

Step 5: Create Controller

Controllers → HomeController.cs

Import required namespaces.

using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;

Fetch Data from SQL Server

public ActionResult Index()
{
    DashboardViewModel vm = new DashboardViewModel();

    string cs = ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString;

    using (SqlConnection con = new SqlConnection(cs))
    {
        con.Open();

        // Fetch Students
        SqlCommand cmd1 = new SqlCommand("SELECT * FROM Students", con);
        SqlDataReader dr1 = cmd1.ExecuteReader();

        List<Student> studentList = new List<Student>();

        while (dr1.Read())
        {
            studentList.Add(new Student
            {
                Id = Convert.ToInt32(dr1["Id"]),
                Name = dr1["Name"].ToString(),
                Age = Convert.ToInt32(dr1["Age"])
            });
        }

        dr1.Close();

        // Fetch Courses
        SqlCommand cmd2 = new SqlCommand("SELECT * FROM Courses", con);
        SqlDataReader dr2 = cmd2.ExecuteReader();

        List<Course> courseList = new List<Course>();

        while (dr2.Read())
        {
            courseList.Add(new Course
            {
                CourseId = Convert.ToInt32(dr2["CourseId"]),
                CourseName = dr2["CourseName"].ToString()
            });
        }

        vm.Students = studentList;
        vm.Courses = courseList;
    }

    return View(vm);
}

Explanation

  • Fetch Students from SQL Server

  • Fetch Courses from SQL Server

  • Store both lists inside DashboardViewModel

Step 6: Create View

Views → Home → Index.cshtml

@model DashboardViewModel

<h2>Student List</h2>

<table border="1">
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
</tr>

@foreach (var item in Model.Students)
{
<tr>
<td>@item.Id</td>
<td>@item.Name</td>
<td>@item.Age</td>
</tr>
}

</table>


<h2>Course List</h2>

<table border="1">
<tr>
<th>Course Id</th>
<th>Course Name</th>
</tr>

@foreach (var item in Model.Courses)
{
<tr>
<td>@item.CourseId</td>
<td>@item.CourseName</td>
</tr>
}

</table>

Explanation

The view receives the DashboardViewModel.

Then it displays:

  • Students table

  • Courses table

Output

The page will display:

Student List
--------------------------------
Id   Name     Age
1    Rahul    20
2    Neha     22

Course List
--------------------------------
CourseId   CourseName
1          C#
2          ASP.NET MVC

Both tables appear on the same view page.

Why Use ViewModel?

ViewModel is used because:

  • MVC views accept only one model

  • Multiple models can be combined using a ViewModel

  • It keeps code clean and organized

Conclusion

In ASP.NET MVC, we cannot directly use multiple models in a single view. The recommended approach is to create a ViewModel that combines all required models.

In this article we learned:

  • How to use multiple models in one view

  • How to create a ViewModel

  • How to fetch data from SQL Server

  • How to display multiple datasets in one page