2

Possible Duplicate:
ASP.NET MVC - View with multiple models

Using ASP.NET MVC 3.0, how can I pass multiple data models from my controller to my view? I'm hoping for an elegant solution...thanks!

BTW - I can provide code samples but I think this is generic enough not to warrant it

Community
  • 1
  • 1

1 Answers1

2

There isn't a truly elegant way to do it, unfortunately. My preferred method is to encapsulate the two objects and send that to the view.

public class City{
public Mall TheMall;
public School TheSchool;
}

Then your view will be strongly typed as City, and you will use Model.TheMall.Property and Model.TheSchool.Property to access what you need.

Another method is to use the ViewData bag. What you can do is populate it like such:

ViewData["City"] = "Toronto";  //random string
ViewData["Mall"] = new TheMall(...);
return View(MyViewName);

And then in your view, you will have access these using the key you assigned in the controller ("City", "Mall", in this case).

Hope that helps!

splatto
  • 3,159
  • 6
  • 36
  • 69
  • 1
    The first method is pretty commonly known as a ViewModel, and usually people will have a ViewModels folder to hold these, separate from the Models folder. I personally call the ModelProjections because it is essentially a layer of abstraction that allows you to compose projections of your model specialized for your UI. – AaronLS Oct 04 '11 at 20:25