views:

392

answers:

1

On my start page, I'd like to display the first items from several different lists that i have on other pages - somewhat like the "recent" page here on SO displays both recent posts and recent comments. In my case I want to list the two most recent posts in a guest book, and the next upcoming event.

In order to do this, how can I pass several Model objects to my View? Is it even possible? If not, how should it be done?

+11  A: 

An alternative to tvanfosson's solution is to create a strongly-typed view so that you get cvompile-time checking and less "magic strings."

Example...

Assume you have the class:

public class FrontPageViewData
{
    public List<Post> Posts { get; set; }
    public List<Comment> Comments { get; set; }
}

Then in your controller...

public ActionResult Index()
{
    FrontPageViewData viewData = new FrontPageViewData();
    viewData.Posts = DB.Posts.ToList();
    viewData.Comments = DB.Comments.ToList();
    return View(viewData);
}

And, finally... in your view. This will allow you to access the passed in view data with intellisense if you setup the view registration line up to use it (notice the part. This means the Model property will be an instance of the passed in viewdata argument into the VIew method in your controller.

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<FrontPageViewData>" %>
<asp:Content ID="MainContent" ContentPlaceHolderID="MainContent" runat="server">
<%= Model.Posts.Count().ToString(); %>
<%= Model.Comments.Count().ToString(); %>
</asp:Content>

Of course this is just a demo and I wouldn't use this code verbatim.

Chad Moran
If you're passing the model to a partial you don't get compile-time checking as the model parameter is of type object. I don't necessarily like the idea of creating a new class just to hold data that could as easily be in an existing container. Why not write a ViewDataWrapper as an abstraction?
tvanfosson
>>...you don't get compile-time checking as the model parameter is of type object...You do have compile-time checking by specifying the type parameter for ViewUserControl
Buu Nguyen
This certainly would my preferred option. Mainly as it creates a level of abstraction between my domain model and the view. Thus I should be able to change the domain model without affection the view or vice a versa.
Colin G
I am using this type of model for the more complex stuff and it's so much cleaner, it's a nice way to do things.
Morph
The calls to ToString() are redundant.
John Sheehan
Because that's the point.
Chad Moran
I second the approach with the ...ViewData classes. I do this all the time and even use the same suffix ("ViewData"). I don't think you can easily avoid this and have compile-time checking too.
Andrei Rinea