Introduction
This tip/trick shows a simple way for passing data between Controller and View. The current tip/trick shows how to pass the result of LINQ query to View, and show its results using foreach
loop.
Background
ASP.NET MVC is an advanced technology from Micrososft for developing web sites, that it provides full separation between View, Controller, and Model layers.
Using the Code
This solution shows few concepts related to ASP.NET can be a good example for beginners in this field. This solution has ideas and solutions related to LINQ , Entity Framework.
First, add item ADO Entity Data Model, and create models on this file using the database.

Above is the ADO Entity Model after generating the models from the database, the model consists of two tables that have one to many relation. The department
has many relations with Employee
. The ADO Entity Model automatically generates the layers of the Model
classes.
In this solution, the employee
s of a certain department
will be returned, the ViewModel
will be created to show the properties of Employees
of department
and properties of the related department
.
The ViewModel
contains property of type IList
, to receive the results of inner Join
query of LINQ, and display its contents on View
.
public class EmployeeDepartment
{
public string departmentName {get;set;}
public string departmentLocation {get;set;}
public string FirstName {get;set;}
public string LastName {get;set;}
public IList EmployeeDepartment MenuItems{get;set;}
}
The controller is responsible for processing the data that is retrieved from the model and passing it to View. So, the controller is the heart of ASP.NET MVC. Passing values from controller to View can be binding controller to view, or using properties using ViewBag
, ViewData
, and TempData
.
public class EmployeeController : Controller
{
public ActionResult Index()
{
return View();
}
public ViewResult ViewEmployee(int DepartmentID)
{
EntityTestEntities context = new EntityTestEntities();
EmployeeDepartment empDepartment = new EmployeeDepartment();
empDepartment.MenuItems = (from employee in context.Employees
join department in context.Departments
on employee.Dep_Id equals department.ID
where employee.Dep_Id == DepartmentID
select new EmployeeDepartment()
{
FirstName=employee.FirstName,
LastName=employee.LastName,
departmentName=department.Location,
departmentLocation=department.Name
}).ToList();
return View(empDepartment);
}
}
The controller EmployeeController
uses the inner join query to retrieve the employees of a certain department
, the search uses the Id
of the department
that is passed using URL and received by the action ViewEmployee
. After that, a view is created for the ViewEmployee
, that is of type List
and the Model
class is ViewModel
that is DepartmentEmployee
class.

@model EntityMVCTest1.Models.EmployeeDepartment
@{
ViewBag.Title = "ViewEmployee";
}
<h2>ViewEmployee</h2>
