Display Multiple Tables In A Single View In ASP.NET MVC
In ASP.NET MVC, displaying data from multiple tables in a single view can be achieved by using a view model. This approach allows for efficient organization and presentation of data without cluttering the view or compromising on code cleanliness.
How to Display Multiple Tables in ASP.NET MVC
Follow these steps to effectively display multiple tables in a single view using ASP.NET MVC:
-
Create Your Models: Define separate models for each table you want to display. For instance, in our example, we have Employee
and Department
models.
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public int DepartmentId { get; set; }
public Department Department { get; set; }
}
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public List<Employee> Employees { get; set; }
}
-
Create a View Model: Next, create a view model that aggregates data from all the models you want to display. This view model acts as a container for passing data to the view.
public class EmployeeDepartmentViewModel
{
public List<Employee> Employees { get; set; }
public List<Department> Departments { get; set; }
}
-
Populate the View Model in the Controller: In your controller action method, populate the view model with data fetched from the database or any other data source.
public ActionResult Index()
{
var employees = GetEmployeesFromDatabase(); // Get employees from database
var departments = GetDepartmentsFromDatabase(); // Get departments from database
var viewModel = new EmployeeDepartmentViewModel
{
Employees = employees,
Departments = departments
};
return View(viewModel);
}
-
Create the View: Finally, create the view (Index.cshtml
in our example) and iterate through the collections of data within the view model to display them in HTML tables.
@model YourNamespace.EmployeeDepartmentViewModel
<h2>Employees</h2>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Department</th>
</tr>
@foreach (var employee in Model.Employees)
{
<tr>
<td>@employee.Id</td>
<td>@employee.Name</td>
<td>@employee.Department.Name</td>
</tr>
}
</table>
<h2>Departments</h2>
<table>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
@foreach (var department in Model.Departments)
{
<tr>
<td>@department.Id</td>
<td>@department.Name</td>
</tr>
}
</table>
By leveraging view models, ASP.NET MVC allows developers to elegantly display data from multiple tables in a single view. This approach enhances code maintainability and readability while providing a seamless user experience.