user1012500
user1012500

Reputation: 1637

Passing multiple models to a view

I'm having problems in passing multiple models to a single view, after reading other posts it I've gathered that I need to create a separate class and instantiate that class and return that instantiated class to the view. However, how would I do this ?

I wanted to use Entity Framework, and Linq to do the queries. If you can provide sample code for me to learn...

Upvotes: 0

Views: 1094

Answers (3)

Maess
Maess

Reputation: 4146

Create a view model. A view model is a model that is typically made up of other models and is not bound to your data model. The MvcMusic demo has a good example of the use of view models.

While ViewData will work its not type safe and basically depends on magic strings, so I would avoid it.

Upvotes: 0

1Mayur
1Mayur

Reputation: 3485

Use

public ActionResult Index()
{
    SomeClass1 object1 = new SomeClass1();
    SomeClass2 object2 = new SomeClass2();
    ViewData["someName1"]=object1;
    ViewData["someName2"]=object2;
    return View(ViewData);
}

In the View page you can access them as:

<% SomeClass1  object1 = ViewData["someName1"] as SomeClass1; %>
<% SomeClass1  object2 = ViewData["someName2"] as SomeClass2; %>

Upvotes: 0

You could either do it the quick and dirty way, using dynamic:

dynamic viewdata = new ExpandoObject();
viewdata.object1 = Model1;
viewdata.object2 = Model2;

return View(viewdata);

Or you could do it properly and create a viewmodel.

class ViewModel1 {
  public MyModel Model1 { get; set; }
  public MyOtherModel Model2 { get; set; }
}

ViewModel1 viewdata = new ViewModel1();
viewdata.Model1 = Model1;
viewdata.Model2 = Model2;

return View(viewdata);

Upvotes: 4

Related Questions