1.

How to use multiple models to a single view in ASP.NET MVC?

Answer»

ASP.NET MVC will PERMIT only a single model to be bound to each view, but there are many workarounds for this. For example, the class ExpandoObject in the ASP.NET framework is a dynamic model which will be passed to a view.

Another common solution is the usage of ViewModel class(a class with SEVERAL models), ViewBag(a property of the ControllerBase class which is dynamic), or ViewData(a dictionary object). It is also possible to use Tuple, JSON, and RenderAction.

In the example given below, you can get to know about how to use multiple models in a single view with the help of the ViewModel class. Here, ViewModel has two properties namely Managers and Employees that acts as a model.

ViewModel class:

public class ViewModel{ public IEnumerable<Manager> Managers { get; set; } public IEnumerable<Employee> Employees { get; set; }}

Controller CODE:

public ActionResult IndexViewModel(){ ViewBag.Message = "Welcome to my example program!"; ViewModel demomodel = new ViewModel(); demomodel.Managers = GetManagers(); demomodel.Employees = GetEmployees(); return View(demomodel);}

View code:

@using MultipleModelInOneView;@model ViewModel@{ ViewBag.Title = "Home PAGE";}<h2>@ViewBag.Message</h2><p><b>Manager List</b></p><table> <tr> <th>ManagerId</th> <th>Department</th> <th>Name</th> </tr> @foreach (Manager manager in Model.Managers) { <tr> <td>@manager.ManagerId</td> <td>@manager.Department</td> <td>@manager.Name</td> </tr> }</table><p><b>Employee List</b></p><table> <tr> <th>EMPLOYEEID</th> <th>Name</th> <th>Designation</th> </tr> @foreach (Employee employee in Model.Employees) { <tr> <td>@employee.EmployeeId</td> <td>@employee.Name</td> <td>@employee.Designation</td> </tr> }</table>


Discussion

No Comment Found