DownLoad Sample Project: MvcViewWithMultipleModels
In mvc programming a view can be associate with multiple models and developers have to send multiple models from controller to cshtml page.There are many common approaches like ViewBag,ViewData,ViewModel etc can be use to achieve this functionality.
But here i am not going to demonstrate all above three approches.you can use .net framework 4.0 new features to pass the multiple models from controller to view effeciently.
- Expendo Object
1.) Using Dynamic Model (Expendo Object):
The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute(“sampleMember”).
Let say you have two models named as “Department” and “Employee” and you want bind these two models with mvc view.Below are the model definitions:
Method details fetch employee and department details as per below:
On the view you have to use dynamic property of .net framework 4.0 and need to be declared as @model dynamic.this is not strongly type of view.
2.) Using Tuples:
In C#, tuples are used to store data. It’s sort of like a variable, but in order for it to be a tuple it must contain more than one value. Each instance of a tuple has a fixed number of items within it (and each item has its own distinct type, eg. a variable or an int), and once the tuple has been created, it can’t be altered in any way.
Let’s continue with previous create models and there are no changes in model class.the only change need to do in controller and view.
Now Controller looks like after code updating for tuples:
you have use tuples at top of the view and you have to declare as per below:
complete view looks like:
You can see there is no change in final rendered output.
This article describes how to pass multiple models from controller to view .I hope this will be helpful for programmers.