Vipul Kumar
Vipul Kumar

Reputation: 416

Pass two models to view without using ViewModel approach

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

Upvotes: 0

Views: 665

Answers (4)

Jeff D
Jeff D

Reputation: 349

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

Upvotes: 0

Carles Company
Carles Company

Reputation: 7216

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.

Upvotes: 0

Teppic
Teppic

Reputation: 2546

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.

Upvotes: 4

Anthony Chu
Anthony Chu

Reputation: 37540

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

Upvotes: 4

Related Questions