Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple models sent to a single view instance

My terminology is probably way off here but basically I'm trying to pass multiple data models to a view. To help put the question in context, take this example:

Say I was making a blog. When I log in I want the home screen to display a list of all new unapproved comments, as well as a list of recently registered users, and a list of the most recently submitted blog posts.

Most discussions I've seen suggest strongly-typing the view page so it can be called with something like "return View(RecentComments)" and iterate through the comments in the view, or to cast the data model like "var NewUsers = (MembershipUserCollection) ViewData.Model". What I'm ideally after is the 'right', or at least a 'right-enough', way of passing multiple models while still maintaining appropriate logic separation.

like image 510
nathanchere Avatar asked Jan 05 '10 02:01

nathanchere


3 Answers

One way is to create a new type that encapsulates both pieces of model data:

public class MyBigViewData {
    public SubData1 SubData1 { get; set; }
    public SubData2 SubData2 { get; set; }
}

public class SubData1 {
    ... more properties here ...
}

public class SubData2 {
    ... more properties here ...
}

Another way is to store the "main" model data as the strongly-typed data and store other data in the view data as dictionary items:

ViewData["username"] = "joe"; // "other" data
ViewData["something"] = "whatever"; // "other" data
ViewData["subdata1"] = new SubData1(...);
return View(myRealModelData);

The advantage of the second approach is that you don't need to do anything special at all: It works right out of the box.

like image 110
Eilon Avatar answered Sep 19 '22 15:09

Eilon


What I've done in the past is written a class that contained instances of both the classes I will need on the view.

ie

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

EDIT

This is an example of what other posters mean by creating an object with both objects as fields/properties

like image 30
splatto Avatar answered Sep 22 '22 15:09

splatto


Sadly, the only way to accomplish passing multiple objects is either by creating an object with both objects as fields/properties, or by using a weakly typed array.

like image 39
David Pfeffer Avatar answered Sep 19 '22 15:09

David Pfeffer