0

I want to know that is it possible to pass two Models simultaneously in a view without using ViewModel approach ?

Vipul Kumar
  • 416
  • 5
  • 17

4 Answers4

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>

Live Demo

Anthony Chu
  • 37,170
  • 10
  • 81
  • 71
  • I thought he does not want to use the ViewModel? – DerApe Sep 05 '14 at 05:46
  • 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