Translate

Wednesday 16 July 2014

Pass Multiple Models in Single View in MVC

How To Pass more than one Models to the single view in MVC


In MVC we cannot pass multiple models from a controller to the single view. This article provides a workaround for multiple models in a single view in MVC.
Suppose I have two models, Employee and Department, and I need to display a list of employers and each department of employee within a single view. How can we do this?

they are two classes and are the model definitions for the Employee and Department classes.

public class Employee{
    public int EmpId{ getset; }
    public string EmpName{ getset; }
public class Department{
    public int DeptId{ getset; }
    public string DeptName{ getset; }  
}
Following methods for both classes
private List<Employee> GetEmployers()
{
    List<Employee> emp= new List<Employee>();
    emp.Add(new Employee{ EmpId= 1000, EmpName = "Jagan" });
    emp.Add(new Employee{ EmpId= 1001, EmpName = "Avinash" });
    emp.Add(new Employee{ EmpId= 1002, 
EmpName = "Sabari" });
    return emp;
public List<Department> GetDepatments(){
    List<Department> depts= new List<Department>();
    depts.Add(new Department{ DeptId= 1, DeptName= "IT" });
    depts.Add(new Department{ DeptId= 2, DeptName= "HR" });
    depts.Add(new Department{ DeptId= 3, DeptName= "Admin" });
    return depts;
}
Solution
There are many ways to use multiple models with a single view. Here I will explain ways one by one.


1. Using ViewModel
2. Using ViewData
3. Using ViewBag
4. Using Tuple
5. Using Dynamic Model
6. Using Render Action


1. Using View Model
ViewModel is nothing but a single class that may have multiple models. It contains multiple models as a property. It should not contain any method.

In the above example, we have the required View model with two properties. This ViewModel is passed to the view as a model. To get intellisense in the view, we need to define a strongly typed view.
public class ViewModel{
    public IEnumerable<Employee> Employers{ get; set; }
    public IEnumerable<Department> Departments{ get; set; }
}
Controller code
 public ActionResult IndexViewModel(){
    ViewModel model = new ViewModel();
    model.
EmployersGetEmployers();
    model.
Departments= GetDepartments();
    return View(model);
}
View code
@using MvcMultipleModelsInView;
@model ViewModel
@{ 
      ViewBag.Title = "Home Page";
}
 
<p><b>Employee List</b></p>

<table>
      <tr>
         <th>EmpId</th>     
          <th>EmpName</th>

      </tr>
@foreach (Employee emp in Model.Employeers)
    {
        <tr>

            <td>@emp.EmpId</td>
            <td>@
emp.EmpName</td>
        </tr>
    }
</table>
 <p><b>Department List</b></p>
    <table>
         <tr>
             <th>DeptId</th>
            <th>DeptName</th>
    </tr>    

@foreach (Department dept in Model.Departments)
    {
        <tr>

             <td>@dept .DeptId</td>
            <td>@dept .DeptName</td>
        </tr>

    }
</table>
2. Using ViewData
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. The Type Conversion code is required when enumerating in the view.
For the preceding example, we need to create ViewData to pass a list of teachers and students from the controller to the view.

Controller Code
public ActionResult IndexViewData(){
    ViewData["Employeers"] = 
GetEmployers();
    ViewData["Departments"] = 
GetDepartments();
    return View();
}
View Code
@using MvcMultipleModelsInView;
@{
    ViewBag.Title = "Home Page";
}
@{
   IEnumerable<Employee> employers= ViewData["Employeers"] as IEnumerable<Employee>;
   IEnumerable<
Department> departments= ViewData["Departments"] as IEnumerable<Department>;
}
<p><b>Employee List</b></p>

<table>
    <tr>
        <th>EmpId</th>     
        <th>EmpName</th>

    </tr>
    @foreach (
Employee emp in employers)
    {
        
<tr>
            <td>@emp.EmpId</td>
            <td>@
emp.EmpName</td>
        </tr>
    

}</table>

 <p><b>Department List</b></p>
 <table>
    <tr>
        <th>DeptId</th>
        <th>DeptName</th>
    </tr>

    @foreach (Department dept in 
departments)
    {
        
<tr>
            <td>@dept .DeptId</td>
            <td>@dept .DeptName</td>
        </tr>

    }

</table>
3. 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.

Controller Code
public ActionResult IndexViewBag()
{
    ViewBag.Message = "Welcome to my demo!";
    ViewBag.Employers= GetEmployers();
    ViewBag.Departments= GetDepartments();
    return View();
}
View Code
@using MvcMultipleModelsInView;
@{
    ViewBag.Title = "Home Page";
}

<p><b>Employee List</b></p>
 <table>
    <tr>
        <th>EmpId</th>     
        <th>EmpName</th>

    </tr>

    @foreach (Employee emp in ViewBag.Employers)
    {
        <tr>
            <td>@emp.EmpId</td>
            <td>@
emp.EmpName</td>
        </tr>
    }

</table>

 <p><b>Department List</b></p>
 <table>
    <tr>
        <th>DeptId</th>
        <th>DeptName</th>
    </tr>
    @foreach (Department dept in ViewBag.Departments)
    {
         <tr>
            <td>@dept .DeptId</td>
            <td>@dept .DeptName</td>
        </tr>

    }

</table>

4. Using Tuple
A Tuple object is an immutable, fixed-size and ordered sequence object. It is a data structure that has a specific number and sequence of elements. The .NET framework supports tuples up to seven elements.

Using this tuple object we can pass multiple models from the controller to the view.

Controller Code
public ActionResult IndexTuple(){
    ViewBag.Message = "Welcome to my demo!";
    var Model = new Tuple<List<Employee>, List<Department>>(GetEmployers(), GetDepartments());
    return View(Model);
}
View Code
@using MvcMultipleModelsInView;
@model Tuple <List<Employee>, List <Department>>

@{
    ViewBag.Title = "Home Page";
}
<p><b>Employee List</b></p>
  <table>
    <tr>
        <th>EmpId</th>     
        <th>EmpName</th>

    </tr>

    @foreach (Employee emp in Model.Item1)
    {
        
 <tr>
            <td>@emp.EmpId</td>
            <td>@emp.EmpName</td>
        </tr>
    }
</table>

 <p><b>Department List</b></p>
  <table>
     <tr>
        <th>DeptId</th>
        <th>DeptName</th>
    </tr>
    @foreach (Department dept in Model.Item2)
    {
        
<tr>
            <td>@dept .DeptId</td>
            <td>@dept .DeptName</td>
        </tr>
    }
</table>

5. Using Dynamic Model

ExpandoObject (the System.Dynamic namespace) is a class that was added to the .Net Framework 4.0 that allows us to dynamically add and remove properties onto an object at runtime. Using this ExpandoObject, we can create a new object and can add our list of teachers and students into it as a property. We can pass this dynamically created object to the view and render list of the teacher and student.

Controller Code
public class HomeController : Controller{
    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to my demo!";
        dynamic mymodel = new ExpandoObject();
        mymodel.Employee= GetEmployers();
        mymodel.Department= GetDepartments();
        return View(mymodel);
    }
}
We can define our model as dynamic (not a strongly typed model) using the @model dynamic keyword.

View Code
@using MvcMultipleModelsInView;
@model dynamic
@{
    ViewBag.Title = "Home Page";
}

<p><b>Employee List</b></p>
  <table>
     <tr>
         <th>EmpId</th>     
        <th>EmpName</th>

    </tr>

    @foreach (Employee emp in Model.Employers)
    {
        <tr>
            <td>@emp.EmpId</td>
            <td>@
emp.EmpName</td>
        </tr>
    }

</table>

 <p><b>Department List</b></p>
    <table>
        <tr>
          <th>DeptId</th>
          <th>DeptName</th>
       </tr>
    @foreach (Department student in Model.Departments)
    {
        <tr>
            <td>@dept .DeptId</td>
            <td>@dept .DeptName</td>
        </tr>

    }

</table>




No comments:

Post a Comment