Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Models in a Single View (C# MVC3)

I'm using C# and MVC3.

I have a page, for example a Student list, that displays the list of students, which is database driven. At the same time my menu is database driven, so I also have to send it to the view.

How can I send both models to a single view?

like image 643
czetsuya Avatar asked Apr 23 '11 10:04

czetsuya


People also ask

Can we use two multiple models with a single view?

Introduction. In MVC we cannot pass multiple models from a controller to the single view.

Can a view have multiple models?

Yes, you can use Tuple (brings magic in view having multiple model).

Can one view have multiple controllers?

Yes, It is possible to share a view across multiple controllers by putting a view into the shared folder. By doing like this, you can automatically make the view available across multiple controllers.


1 Answers

You should always create separate ViewModels for your views. There should be an abstraction from your Views to your Domain Models. In the demos/tutorials they show it all pretty and easy by simply strongly typing the Views to Domain Models but that's not a good strategy. The views should not be dependent on the business objects.

You should implement David Glenn's proposed solution for your current scenario and also for all other views even if requires mapping the domain model to to another view model class.

EDIT:

If you have lets say a top Menu > TopMenu.aspx And you have multiple partial views inside it > StudentMenu.ascx, ResultMenu.ascx

You will create a View Model for Top Menu > TopMenuViewModel.cs And you will also create view models for partial views > StudentMenuViewModel , ResultMenuViewModel etc.

and your TopMenuViewModel will have both >

class TopMenuViewModel 
{
   //all the stuff required in TopMenu.aspx
   StudentMenuViewModel studentvm;
   ResultMenuViewModel resultvm;
}

and in TopMenu.aspx when rendering the partial you will pass the relevant view model >

Html.RenderPartial('StudentView', Model.studentvm)

Hope it makes sense

like image 81
neebz Avatar answered Sep 28 '22 18:09

neebz