0

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...

user1012500
  • 1,547
  • 1
  • 16
  • 31

3 Answers3

4

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);
Christian Wattengård
  • 5,543
  • 5
  • 30
  • 43
0

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; %>
1Mayur
  • 3,419
  • 5
  • 40
  • 64
  • I would go for the other answer and use a sub ViewModel. All these magic strings and casting could/will be a pain to debug and only gives runtime errors. – Syska Nov 03 '11 at 12:44
  • @Syska "dynamic" keyword is introduced in c# 4.0! what about previous frameworks then? – 1Mayur Nov 03 '11 at 12:52
  • Then I would still go for the ViewModel that contains the 2 other view models. I dont really see the gain of this, unless you are just trying out some things in a little local project. I also started doing this, but in the end ... a really nightmere. I would avoid using dynamic if it can be done, unless we can some intellisence like R# is trying to provide, so we can catch errors in the build process. – Syska Nov 03 '11 at 16:49
0

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.

Maess
  • 4,118
  • 20
  • 29