I want to know that is it possible to pass two Models simultaneously in a view without using ViewModel approach ?
Asked
Active
Viewed 664 times
0
-
possible answer is here [Pass two models to a view][1] [1]: http://stackoverflow.com/questions/17030399/pass-two-models-to-view – Zohaib Aslam Sep 05 '14 at 05:26
-
@ZohaibAslam I know very well that I can do that with ViewModel approach.But I don't want to use the ViewModel. – Vipul Kumar Sep 05 '14 at 05:30
-
1I think viewmodel is the best approach but i have used a class once you can check it out "Tuple". This class can contain different types. – Mairaj Ahmad Sep 05 '14 at 05:37
-
Why do you want to do that in the first place? – DerApe Sep 05 '14 at 05:47
4 Answers
4
I guess you can use a Tuple<T1, T2>
...
public ActionResult Index()
{
return View(new Tuple<Foo, Bar>(new Foo(), new Bar()));
}
View:
@model Tuple<Foo, Bar>
...
<div class="container">
Foo value = @Model.Item1.Value
<hr />
Bar value = @Model.Item2.Value
</div>

Anthony Chu
- 37,170
- 10
- 81
- 71
-
-
I took that to mean he/she doesn't want to create a view model class (which I think is a better practice), but still wants to pass the two models to the view without using dynamics (e.g., ViewBag). – Anthony Chu Sep 05 '14 at 05:49
-
@derape Actually Someone asked about this..so i am curious to know Is it only this way or there is another way..:) – Vipul Kumar Sep 19 '14 at 04:47
4
If you don't need to worry about binding then you can just use the ViewBag, e.g.
public ActionResult Index()
{
ViewBag.FirstModel = new FirstModel();
ViewBag.SecondModel = new SecondModel();
return View();
}
The models are then available in the view via the ViewBag.

Teppic
- 2,506
- 20
- 26
0
Use TempData
or ViewData
. You can even use Session or Cache. I prefer the ViewModel approach though as it is what it's intended for. I tend to only use TempData or ViewData to fill in select lists.

Carles Company
- 7,118
- 5
- 49
- 75
0
Other possible ways are by using the following
ViewData ViewBag TempData
Here is the whole code sample for each, take a look. hope it helps
Passing multiple models to view using ViewData, ViewBag, TempData

Jeff D
- 349
- 3
- 4