Multiple Models in a Single View (C# MVC3)

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

Leave a Comment