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?
Introduction. In MVC we cannot pass multiple models from a controller to the single view.
Yes, you can use Tuple (brings magic in view having multiple model).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With